C#中的Attribute
阿新 • • 發佈:2022-03-29
一、簡介
特性(Attribute):相當於標籤,貼上標籤就產生了新功能。可以這樣簡單理解。
二、常見系統特性
- [Required]
- [Display(Name = "密碼")]
- [StringLength(100, ErrorMessage = "{0} 必須至少包含 {2} 個字元。", MinimumLength = 6)]
- [DataType(DataType.Password)]
- [Compare("Password", ErrorMessage = "密碼和確認密碼不匹配。")]
- [DebuggerStepThrough]
三、定義特性
特性就是一個類,定義時需要繼承Attribute
[AttributeUsage(AttributeTargets.Field)]//限制特性只能應用於欄位 public class RemarkAttribute:Attribute//必須繼承Attribute類 { /// <summary> /// 狀態特性 /// </summary> /// <param name="remark"></param> public RemarkAttribute(string remark)//建構函式 { this.Remark = remark; } public string Remark { get; private set; }//屬性 }
四、使用特性
列舉值上使用特性
public enum UserState { /// <summary> /// 正常 /// </summary> [Remark("正常")] Normal=0, /// <summary> /// 凍結 /// </summary> [Remark("凍結")] Frozen =1, /// <summary> /// 刪除 /// </summary> [Remark("刪除")] Deleted =2 }
五、呼叫特性實現
public class AttributeInvoke
{
public string GetRemark( UserState userState)
{
Type type = userState.GetType();
var fileId = type.GetField(userState.ToString());
if (fileId.IsDefined(typeof(RemarkAttribute),true))
{
RemarkAttribute remarkAttribute=(RemarkAttribute)fileId.GetCustomAttribute(typeof(RemarkAttribute), true);
return remarkAttribute.Remark;
}
else
{
return userState.ToString();
}
}
}
六、呼叫測試
AttributeInvoke attributeInvoke = new AttributeInvoke();
Console.WriteLine(attributeInvoke.GetRemark(userState));