列舉型別算是我們在程式裡面常用的東西,尤其是很多不同種類的狀態判斷,在避免手誤上有很大的好處;可是如果要配合文字顯示,雖然可以直接利用toString,但似乎沒有這麼好用,這時候如果利用自訂屬性就可以再增加活用。
列舉型別算是我們在程式裡面常用的東西,尤其是很多不同種類的狀態判斷,在避免手誤上有很大的好處;可是如果要配合文字顯示,雖然可以直接利用toString,但似乎沒有這麼好用,這時候如果利用自訂屬性就可以再增加活用。
以下的範例是利用.NET 2.0寫的,如果是.NET 3.5以上利用Extension Methods會更漂亮。
首先先定義屬性:
public class MsgAttribute : Attribute
{
#region Properties
/// <summary>
/// Holds the Msg for a value in an enum.
/// </summary>
public string Msg { get; protected set; }
#endregion
#region Constructor
/// <summary>
/// Constructor used to init a Msg Attribute
/// </summary>
/// <param name="value"></param>
public MsgAttribute(string value)
{
this.Msg = value;
}
#endregion
}
接下來在列舉上面使用:
public enum ValidePIN
{
[Msg("密碼正確")]
Correct,
[Msg("密碼錯誤")]
Error,
[Msg("密碼已鎖定")]
Lock
}
取得值的方法:
public static string GetMsg(Enum value)
{
Type type = value.GetType();
FieldInfo fieldInfo = type.GetField(value.ToString());
MsgAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(MsgAttribute), false) as MsgAttribute[];
return attribs.Length > 0 ? attribs[0].Msg : null;
}
參考來源: