什么是特性?
[Obsolete("不要用無參構造函數",true)] 放在方式上, 該方法就不能使用了
[Serializable]放在類上面。該類就是可以序列化和反序列化使用了。
在命名空間、類、方法、屬性、字段、枚舉 上用中括號[]
自定義特性,特性就是類:必須繼承Attribute 或者是Attribute的泛生類
public class SizeAttribute : Attribute // 這個就是一個自定義特性
{
public SizeAttribute()
{
Console.WriteLine("這是一個SizeAttribute的構造函數");
}
}
這個特性就創建好了
在其他類, 如Student類上
[SizeAttribute] //在類上寫特性
public class Student
{
[SizeAttribute] //在屬性上寫特性
public int Id{set; get;}
public string Name{set;get}
[SizeAttribute] //在方法上寫特性
public void Show()
{
Console.WriteLine("Show")
}
}
當然特性 也可以有描述自己特性的辦法
就是在特性上面寫上
[AttributeUsage(AttributeTargets.All,AllowMultiple =false,Inherited =true)]
public class SizeAttribute : Attribute
{
}
//意思是當前特性包含所有類型都可以使用,只能單一使用,可以繼承
特性:
1.當程序編譯和執行,特性和注釋的效果是一樣的,沒有任何不同
2.特性編譯后是metadata,只有在反射的時候,才能使用特性。
3.特性可以做權限檢測,屬性驗證,封裝枚舉等很多功能。
4.特性是一個類,可以用作標記元素,編譯時生成在metadata里,平時不影響程序的運行,除非主動用反射去查找,
可以得到一些額外的信息和操作,提供了更豐富擴展空間,特性可以在不 破壞類型封裝的前提下,額外增加功能。
例子:有一個學生類,希望用特性,讓添加的學生年齡不能小於12歲,大於20歲
//學生類
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
[Obsolete("不要用無參構造函數",true)] //這個特性,是不能使用無參構造函數
public Student()
{ }
public Student(int id, string name,int age)
{
this.Id = id;
this.Name = name;
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
[Obsolete("不要用無參構造函數",true)] //這個特性,是不能使用無參構造函數
public Student()
{ }
public Student(int id, string name,int age)
{
this.Id = id;
this.Name = name;
[ControlAgeAttribute(_vMin=12,_vMax=30)] //要判斷年齡,年齡小於20,大於12, 就將下面自定義的特性放在這個屬性上面
this.Age = age;
}
public void Show()
{
Console.WriteLine("這個show方法");
}
}
this.Age = age;
}
public void Show()
{
Console.WriteLine("這個show方法");
}
}
//控制年齡的特性 :特性的命名規范--名稱后面為Attribute
public class ControlAgeAttribute : Attribute
{
public int _vMin{get;set;}//最小年齡
public int _vMax{get;set;} //最大年齡
public bool CompareAge(int age)
{
return age>_vMin && age <_vMax ? true : false; //
}
}
//反射使用特性---用靜態方法
public static class Manage
{
public static bool CompareAgeManage(this Student stu)
{
bool result = false;
Type type = typeof(stu);//先獲取類型
ProperyInfo prop = type.GetProperty("Age");//反射獲取年齡屬性
if (prop.IsDefined(typeof(ControlAgeAttribute ),true))//判斷當前屬性是否有ControlAgeAttribute 的特性
if (prop.IsDefined(typeof(ControlAgeAttribute ),true))//判斷當前屬性是否有ControlAgeAttribute 的特性
{
ControlAgeAttribute attribute = (ControlAgeAttribute) prop.GetCustomAttribute(typeof(ControlAgeAttribute ),true);
//獲取特性
result = attribute.CompareAge(stu.Age);
return result;//得到結果返回
}
return result;
}
}
//控制台Main方法里面執行
static void Main(string[] args)
{
Student student = new Student(12,"hahaha",15);
Console.WriteLine(student.CompareAgeManage()); //15在12和20 之間,所以是True;
}
{
Student student = new Student(12,"hahaha",15);
Console.WriteLine(student.CompareAgeManage()); //15在12和20 之間,所以是True;
}