C#高级学习第四章反射和特性

来源:互联网 发布:matlab遗传算法工具箱 编辑:程序博客网 时间:2024/06/05 11:43

Type:

Type类是抽象类,它能获取它对应类的所有成员(public)

MyClass my=new MyClass();

Type type=my.GetType();   通过对象获取这个对象所属类的Type对象

type.Name  获取类的名字

type.Namespace 获取所属命名空间

type.Assembly 获取程序集

FieldInfo[] array=type.GetFields() 获取这个类的所有字段(public) public int age   using System.Reflection

PropertyInfo[] array2=type.GetProperties()  获取这个类的所有属性 public string name{get;set;}

MethodInfo[] array3=type.GetMethods()  获取这个类的所有方法


Assembly 程序集:

MyClass my=new MyClass();

Assembly assem= my.GetType().Assembly; 通过类的type对象获取他所在的程序集

assem.FullName  项目名 (exe)

Type[] types=assem.GetTypes();

foreach(var type in types)

{

  Debug.Log(type);     输出程序集的对象

}


Obsolete特性 代表弃用

[Obsolete("这个已经过时了,请用New Method")]   代表这个方法已经过时了,被弃用了,可以添加注释

[Obsolete("这个已经过时了,请用New Method",true)]  后面bool为true,则代表这个方法不能在用了


Conditional:

[Conditional("IsText")]     没有定义IsText,被condition修饰的所有的方法都被隐藏

#define IsText   定义了IsText 方法都显现出来


调用者信息特征:

public void PrintOut(string Message,[CallerFilePath]string fileName="",[CallerLineNumber]int lineNumber=0,[CallerMemberName]methodName="")

{

  Debug.Log(Message);

  Debug.Log(fileName);

  Debug.Log(lineNumber);

  Debug.Log(methodName);

}


DebuggerStep Through:

[DebuggerStep Through]

可以跳过debugger的单步调试,不让进入该方法(当我们确定这个方法没有任何错误的时候,可以使用这个),放在方法前面


创建自定义特性:

1.特性类的后缀以Attribute结尾

2.需要继承自System.Attribute

3.一般情况下声明为sealed

4.一般情况下,特性类用来表示目标结构的一些状态(定义一些字段或者属性,一般不定义方法)

[AttributeUsage(AttributeTargets.Class)] 表示该特性类可以应用到的程序结构有哪些

sealed class MyTestAttribute:System.Attribute

{

    public string Description{get;set;}

    public int ID{get;set;}

    public MyTestAttribute(string des)

  {

       this.Description=des;

  }

}


使用:

通过制定属性的名字,给属性赋值,这种是命名参数 如ID=100

[MyTest("简单的特性类",ID=100)] 当我们使用特性的时候,后面的Attribute不用写,会自己加上

Type type=typeof(Program); 通过typeof+类名也可以获取type对象

object[] array = type.GetCustomAttributes(false)  得到类的特性

MyTestAttribute mytest=array[0] as MyTestAttribute;  转换成这个特性

Debug.Log(mytest.Description);

Debug.Log(mytest.ID);



[Serializable]  使创建的类可视化