标志的定义
1、标识符(类名、方法名等)是程序员写给自己或其他程序员看的
2、程序无法通过标识符知道其自身的含义
3、但是我们可以使用标志来标记标识符的含义,程序可以读取标志从而得知一个标识符的含义
4、标志就像一本字典给每个字做的注解
class ABC
{
public ABC(string s)
{
}
}
[ABC("这是标志")] ==> new ABC("这是标志")
反射的定义
反射:在程序运行时可以指导一个类有哪些成员,每个成员方法上有哪些标志、几个参数、每个参数的类型、返回值类型
class CommentAttribute : Attribute
{
public string s;
public CommentAttribute(string s)
{
this.s = s;
}
}
class ABCAttribute : Attribute
{
public string s;
public ABCAttribute(string s)
{
this.s = s;
}
}
//2、可以给类或者方法等加上一个标志
[Comment("游戏对象的基类")]//=>new CommentAtteribute("游戏对象的基类")
class GameObject
{
public int i;
public float H { get; set; }
[Comment("这是一个方法")]
[ABC("这是一个ABC")]
public void f()
{
}
}
class Program
{
static void Main(string[] args)
{
//取得一个类的信息:typeof(类名),返回:类的成员信息类
TypeInfo ti = typeof(GameObject).GetTypeInfo();
//取得类名:
Console.WriteLine(ti.Name);
//取得类中的成员
MemberInfo[] miArray = ti.GetMembers();
for (int i = 0; i < miArray.Length; i++)
{
MemberInfo mi = miArray[i];//取得成员数组中的第i个成员
Console.WriteLine("Name={0},Type={1}",mi.Name,mi.MemberType);//取得该成员的名称
object[] attrs = mi.GetCustomAttributes(false);
//返回一个标志数组,虽然是object数组,但其中存放的内容实际上一定是从Attribute继承的对象
for (int j = 0; j < attrs.Length; j++)
{
object attr = attrs[j];//取得标志数组中的第i个标志
if (attr is CommentAttribute)
{
CommentAttribute ca = (CommentAttribute)attr;
Console.WriteLine(ca.s);
}
else if (attr is ABCAttribute)
{
ABCAttribute abc = (ABCAttribute)attr;
Console.WriteLine(abc.s);
}
}
}
Console.ReadLine();
}
}
GetCustomAttributes(false)
确定是否有自定义标志