使用Attribute注册所有特性

来源:互联网 发布:朝鲜核试验的影响知乎 编辑:程序博客网 时间:2024/06/05 20:56

一、定义一个拥有Attribute特性的基类

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]public class ClassTypeRegisterAttributeBase : System.Attribute{public virtual void Register(System.Type ClassType){}}

二、真正执行操作的子类

子类A

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]public class GameEffectRegister : ClassTypeRegisterAttributeBase{public override void Register(Type AttachedClass){base.Register(AttachedClass);GameEffectFactory.GameEffectClassList.Add(new System.Collections.Generic.KeyValuePair<PKG.EffectType, Type>(EffectType, AttachedClass));}public PKG.EffectType EffectType { get; set; }}

子类B

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]public class ItemEffectRegister : ClassTypeRegisterAttributeBase{public override void Register(Type ClassType){base.Register(ClassType);ItemEffectTypes.Types.Add(ClassType);}public PKG.EffectType EffectType;}




三、注册所有拥有继承了ClassTypeRegisterAttributeBase 特性的类,这里只列举了其中一个

public class ClassTypeRegister{/// <summary>/// 只处理一次/// </summary>static ClassTypeRegister(){var Asm = Assembly.GetExecutingAssembly();//获取所有程序集var AllTypes = Asm.GetTypes(); //获取所有类型for (int i = 0; i < AllTypes.Length; i++){var Type = AllTypes[i];var Processors = Type.GetCustomAttributes(typeof(ClassTypeRegisterAttributeBase), true) as ClassTypeRegisterAttributeBase[];//获取继承了基类<span style="font-family: Arial, Helvetica, sans-serif;">ClassTypeRegisterAttributeBase的类的类型</span>if (Processors.Length > 0) //判断是否存在{for (int j = 0; j < Processors.Length; j++){Processors[j].Register(Type); //调用子类的register接口}mClassList.Add(Type);}}}public static void StaticRegister(){//留空即可}public static IEnumerator<System.Type> GetEnumerator(){return mClassList.GetEnumerator();}protected static List<System.Type> mClassList = new List<Type>();}


0 0
原创粉丝点击