C# Attribute 特性 (入门)

特性(Attribute)是用来 向程序添加声明性信息。一个声明性标签是通过放置在它所应用的元素前面的方括号([ ])来描述的。
特性(Attribute)用于添加元数据,如编译器指令和注释、描述、方法、类等其他信息。所以要获取某个类的特性,需要通过反射实现。举个简单的例子:

1、自定义一个 CheckCodeAttribute
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]

public class CheckCodeAttribute : System.Attribute

{

public string UserName = "";

public string CheckTime = "";

public int Score = 0;

public CheckCodeAttribute(string name,string time,int score)

{

UserName = name;

CheckTime = time;

Score = score;

}

public double GetScore()

{

return Score * 0.8;

}

}
2、将上面的自定义Attribute应用于 一个类上

 [CheckCode("张伟", "2017-03-22",99)]

public class DoWork

{

public string GetData()

{

return DateTime.Now.ToString("yyyy-MM-dd");

}

}

3、通过反射 来获取 DoWork 类相关的 Attribute 信息

static void Main(string[] args)

{

System.Reflection.MemberInfo info = typeof(DoWork);

CheckCodeAttribute att = (CheckCodeAttribute)Attribute.GetCustomAttribute(info, typeof(CheckCodeAttribute));

double score = att.GetScore();

System.Console.WriteLine(att.UserName + " 于 " + att.CheckTime + " 检查了代码,得分:" + score); Console.ReadKey();

}

猜你喜欢

转载自blog.csdn.net/w10101010_y/article/details/84996752