反射
程序在运行时,可以查看其它程序集或其本身的元数据。一个运行的程序查看本身的元数据或者其他程序集的元数据的行为叫做反射。
MyClass.cs
class MyClass// 定义一个用来反射查找的元数据
{
private int age;
private int id;
public int number;
public string Name { get; set; }
public void Test()
{
}
}
Program.cs
static void Main(string[] args)
{
//MyClass my = new MyClass();
//Type type = my.GetType();
Type type = typeof(MyClass);//得到程序的type对象
Console.WriteLine(type.Name);//获取类的名字
Console.WriteLine(type.Namespace);//获取命名空间
Console.WriteLine(type.Assembly);//获取程序集
FieldInfo[] array = type.GetFields();//获取类型的字段列表,返回值是一个数组
foreach (FieldInfo info in array)//遍历输出数组中的内容
{
Console.WriteLine(info.Name+" ");
}
PropertyInfo[] array1 = type.GetProperties();//获取类型的属性列表
foreach (PropertyInfo info in array1)
{
Console.WriteLine(info.Name+" ");
}
MethodInfo[] array3 = type.GetMethods();//获取类型的方法列表
foreach (MethodInfo info in array3)
{
Console.WriteLine(info.Name+" ");
}
Console.ReadKey();
}
特性
特性(attribute)是一种允许我们向程序的程序集增加元数据的语言结构。它是用于保存程序结构信息的某种特殊类型的类。
[Obsolete]:这个特性用来提示程序员这个方法过时,后面值设置True表示调用方法会报错
[Obsolete("方法过时了,请使用新方法",true)]
[Conditional]:这个特性需要先引用using System.Diagnostics;这个命名空间,作用是决定这个方法在程序中是否生效
[Conditional("IsTest")]//#define IsTest//需要在开头位置定义一个宏,使用宏来决定是否调用Test方法
[DebuggerStepThrough]:可以跳过debugger的单步调试,不让进进入该方法
//引用using System.Runtime.CompilerServices;这个命名空间,输出这个方法的文件路径,行数和方法名
static void PrintOut(string str, [CallerFilePath]string fileName = "", [CallerLineNumber]int lineNumber = 0, [CallerMemberName]string methodName = "")
{
Console.WriteLine(str);
Console.WriteLine(fileName);
Console.WriteLine(lineNumber);
Console.WriteLine(methodName);
}
自定义特性
//1.特性类的后缀以Attribute结尾
//2.需要继承自System.Attribute
//3.一般情况下声明为sealed
//4.一般情况下特性类用来表示目标结构的一些状态(定义一些字段或者属性,一般不定义方法)
[AttributeUsage(AttributeTargets.Class)]//AttributeTargets.Class中(.Class)这个后缀用来表示这个特性类指定的目标
//(.Method)表示这个特性类指定方法,(.Property)这个特性类指定属性
sealed class MyTestAttribute:System.Attribute
{
public string Description { get; set; }
public string VersionNumber { get; set; }
public int ID { get; set; }
public MyTestAttribute(string des)
{
this.Description = des;
}
}
在Program中使用自定义特性
[MyTest("Hello",ID =100)]//当我们使用特性类的时候后缀Attribute不用写