反射
可以通过 type来获取类的信息(名字,所在命名空间,所在的程序集,有哪些字段,属性,方法等)
using System.Reflection;//反射要调用的命名空间
Type type = myClass.GetType();//获取一个类的Type
FieldInfo[] array1 = type.GetFields();//获取type中的所有字段名
PropertyInfo[] array2 = type.GetProperties();//获取type中的所有属性名
MethodInfo[] array3 = type.GetMethods();//获取type中的所有方法名
特性
[Obsolete("使用新方法代替")]//表示方法已被弃用
static void OldMethod()
{
....
}
[Conditional("IsTest")]//需要命名空间System.Diagnostics 若没有定义字符串中的宏,则方法不会被调用
void Test()
{
....
}
调用者信息特性
需要命名空间System.Runtime.CompilerServices
可以输出文件路径名,代码行数,调用的方法名
public static void PrintOut(string message,[CallerFilePath] string fileName = "" ,[CallerLineNumber]int lineNumber=0,[CallerMemberName]string MemberName="")
{
Console.WriteLine(message);
Console.WriteLine(fileName);
Console.WriteLine(lineNumber);
Console.WriteLine(MemberName);
}
自定义特性
- 特性类后缀以Attribute结尾
- 需要继承自System.Attribute
- 一般情况下声明为sealed(表示无法被继承的)
- 一般情况下特性类用来表示目标结构的一些状态
using System.Attribute;
[AttributeUsage(AttributeTargets.Class)]//表示该特性类可以应用的程序结构有哪些 这里选择了类类型
sealed class MyTestAttribute : Attribute
{
public string Des { get; set; }
public string VersionNumber { get; set; }
public int ID { get; set; }
public MyTestAttribute(string des)
{
this.Des = des;
}
}
....
[MyTest("特性类",ID =100)]
class Program
....
Type type = typeof(Program);
Object[] array = type.GetCustomAttributes(false);//获取该type的所有特性
MyTestAttribute myTest = array[0] as MyTestAttribute;
Console.WriteLine(myTest.Des+" "+myTest.ID);