//定義:一個類別繼承Attribute 就是特性 //一般以Attribute結尾,宣告時可以省略掉
public class CustomAttribute:Attribute
{
}
[Custom]
public class Student
{
public int Id{get;set;}
public string Name{get;set;}
public void Study()
{
Console.WriteLine($"這裡是{this.Name}跟者老師學習");
}
public string Answer(string name)
{
return $"This is {name}";
}
}
[AttributeUsage(AttributeTargets.All,AllowMultiple = true)]=>讓宣告可以多重修飾某個元素
public class CustomAttribute:Attribute
{
public CustomAttribute()
{}
public CustomAttribute(int id)
{}
public string Description{get;set;}
public string Remark = null;
public void Show()
{
Console.WriteLine($"This is{nameof(CustomAttribute)}");
}
}
[Custom] 完全一樣的,表示都是使用無參數的建構子
[Custom()] 完全一樣的,表示都是使用無參數的建構子
[Custom(123)]帶參數的建構子
[Custom(123),Custom(123, Description ="123")] 多重修飾
[Custom(123, Description ="123",Remark ="2345")] //方法不行
public class Student
{
public int Id{get;set;}
public string Name{get;set;}
public void Study()
{
Console.WriteLine($"這裡是{this.Name}跟者老師學習");
}
[Custom] //方法加上特性
[return:Custom()] //給方法返回值加上特性
public string Answer([Custom] string name)//給參數也加上特性
{
return $"This is {name}";
}
}
使用反射找特性
public class Manager
{
public static void Show(Student student)
{
Type type =typeof(Student);//student.GetType();
if(type.IsDefined(typeof(CustomAttribute),true))//檢查有沒有 性能高
{
CustomAttribute attribute = (CustomAttribute)type.GetCustomAttribute(typeof(CustomAttribute),true);
Console.WriteLine($"{attribute.Description}_{attribute.Remark}");
attribute.Show();
}
public class Student
{
public int Id{get;set;} //可以做長度檢查的特性
public string Name{get;set;} //範圍10001~999999999999
[LongAttribute(10001,999999999999)]
public long QQ{get;set;}
public void Study()
{
Console.WriteLine($"這裡是{this.Name}跟者老師學習");
}
[Custom] //方法加上特性
[return:Custom()] //給方法返回值加上特性
public string Answer([Custom] string name)//給參數也加上特性
{
return $"This is {name}";
}
}
public class Manager
{
public static void Show(Student student)
{
Type type =typeof(Student);//student.GetType();
if(type.IsDefined(typeof(CustomAttribute),true))//檢查有沒有 性能高
{
CustomAttribute attribute = (CustomAttribute)type.GetCustomAttribute(typeof(CustomAttribute),true);
Console.WriteLine($"{attribute.Description}_{attribute.Remark}");
attribute.Show();
}