using System;
namespace ConsoleApplication2
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
System.Reflection.MemberInfo info=typeof(MyClass); //这个东西是一个关于类的反馈信息
MyAttribute att = (MyAttribute)Attribute.GetCustomAttribute(info,typeof(MyAttribute));//这个东西得到了这个类的这个属性
if(att!=null){
Console.WriteLine("MyAttribute.a :{0}",att.a);
Console.WriteLine("MyAttribute.b :{0}",att.b);
}
//
// TODO: 在此处添加代码以启动应用程序
//
}
}
[AttributeUsage(AttributeTargets.Class)]
public class MyAttribute : Attribute{
public int a;
public string b;
public MyAttribute(int a,string b){
this.a = a;
this.b = b;
}
}
[MyAttribute(5,"hello attribute world")]
public class MyClass{
}
}
关于元数据attribute的作用域,可以使类,也可以为函数,如下就是那个枚举类型的定义。
public enum AttributeTargets
{
All=16383,
Assembly=1,
Module=2,
Class=4,
Struct=8,
Enum=16,
Constructor=32,
Method=64,
Property=128,
Field=256,
Event=512,
Interface=1024,
Parameter=2048,
Delegate=4096,
ReturnValue=8192
}
这个东西确实有一点像形容词和副词,对于类的自身的信息有一些描述。有点意思。