C#特性的学习(一)
1.预定定义特性之一:AttributeUsage
AttributeUsage有三个属性:
第一个属性:ValidOn 规定特性可被放置的语言元素,默认是AttributeTargets.All。
第二个属性:AllowMultiple 属性(property)提供一个布尔值。如果为 true,则该特性是多用的。默认值是 false(单用的)。
第三个属性:Inherited 属性(property)提供一个布尔值。如果为 true,则该特性可被派生类继承。默认值是 false(不被继承)。
2.Attribute 特性的实例
[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.7;
}
}
[CheckCode("張三","2018-05-02",100)]
public class Dowork
{
public string GetData()
{
return DateTime.Now.ToString("yyyy-mm-dd");
}
}
class Program
{
static void Main()
{
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();
}