一、反射
反射指程序可以访问、检测和修改它本身状态或行为的一种能力。
1、实列代码
环境准备
class MyClass
{
private int I;
private string S;
public int I1;
public string S1;
private int I2 { get; set;}
private string S2 { get; set;}
public int I3 { get; set; }
public string S3 { get; set; }
private void Test1() { }
private void Test2() { }
public void Test3() { }
public void Test4() { }
}
Tpye类
static void Main(string[] args)
{
MyClass mc = new MyClass();
Type tp = mc.GetType();//Type只得到该类型,当前类的具体的值与Type无关。
Console.WriteLine(tp.Name);//输出类名
Console.WriteLine(tp.Namespace);//输出所在命名空间
Console.WriteLine(tp.Assembly);//输出assembly程序集
FieldInfo[] array1 = tp.GetFields();//得到该类的全部字段(即不带get和set的属性)
foreach(var i in array1)
{
Console.WriteLine(i.Name);
}
PropertyInfo[] array2 = tp.GetProperties();//得到该类的全部属性
foreach(var i in array2)
{
Console.WriteLine(i.Name);
}
MethodInfo[] array3 = tp.GetMethods();//得到该类的全部方法
foreach(var i in array3)
{
Console.WriteLine(i.Name);
}
Console.ReadKey();
输出结果展示
二、特性
1、Obsolete
[Obsolete("过时的放法,请用NewMeth代替")]
static void OldMeth()
{
Console.WriteLine("OldMeth");
}
static void NewMeth()
{
Console.WriteLine("NewMeth");
}
当调用OldMeth方法时
2、Conditional
[Conditional("debug")]
static void NewMeth()
{
Console.WriteLine("NewMeth");
}
当不存在 #define debug 时对NewMeth的调用无效。
3、调用者信息特性
static void Call(string str,[CallerFilePath] string filePath = "",[CallerLineNumber] int lineNumeber=1,[CallerMemberName] string menberName="")
//后三个被特性标记的参数将系统自动传参
{
Console.WriteLine(str);
Console.WriteLine(filePath);
Console.WriteLine(lineNumeber);
Console.WriteLine(menberName);
}
输出结果
3、DebuggerStepThrough 目标函数将在调试的 逐语句调试时跳过该函数内部
[DebuggerStepThrough]
1、创建自定义特性
//1、特性类使用Attribute结尾
//2、需要继承自System.Attribute
//3、一般情况声明为sealed
//4、一般情况特性类用来表示目标结构的一些状态(定义一些字段或者属性,一般不定义方法)
{
[AttributeUsage(AttributeTargets.Class)]//表明该特性类可以应用到的程序结构
sealed class MyTestAttribute : Attribute
{
public string Description { get; set; }
public int Id { get; set; }
public MyTestAttribute(string str)
{
Description = str;
}
}
程序结构的特性类
[MyTest("nihao",Id = 0)]
class MyClass
Type tp = typeof(MyClass);
Object[] atb = tp.GetCustomAttributes(false);
MyTestAttribute mta = atb[0] as MyTestAttribute;
Console.WriteLine(mta.Id);