[C #] enum type custom messages

Enumeration type program in which we considered common thing, especially a lot of different kinds of status determination, in the wrong hands to avoid a great advantage; but if you want to fit text display, although you can directly use toString, but it does not seem so good by this time if you can use custom attributes to add inflect.


Enumeration type program in which we considered common thing, especially a lot of different kinds of status determination, in the wrong hands to avoid a great advantage; but if you want to fit text display, although you can directly use toString, but it does not seem so good by this time if you can use custom attributes to add inflect.

The following example is written using the .NET 2.0, .NET 3.5 if it is more than the use of Extension Methods will be more beautiful.

First, define attributes:

public class MsgAttribute : Attribute
{
    #region Properties

    /// 
    /// Holds the Msg for a value in an enum.
    /// 
    public string Msg { get; protected set; }

    #endregion

    #region Constructor

    /// 
    /// Constructor used to init a Msg Attribute
    /// 
    /// 
    public MsgAttribute(string value)
    {
        this.Msg = value;
    }

    #endregion
}

Next, use the above enumeration:

public enum ValidePIN
{
    [Msg("密码正确")]
    Correct,
    [Msg("密码错误")]
    Error,
    [Msg("密码已锁定")]
    Lock
}

Value acquisition method:

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;
}

Reference Source:

Enum With String Values In C#

Dotblogs Tags: C #, Enum

Original: Large column  [C #] enum type custom messages


Guess you like

Origin www.cnblogs.com/chinatrump/p/11458530.html
Recommended