开发者

How to read enum value in ASP.Net?

My enum structure is this

public enum UserRole
{
    Administrator = "Administrator",
    Simple_User = "Simple User",
    Paid_User = "Paid User"
}

Now i want to read this enum value by using its name suppose

String str = UserRole.Simple_User;

it gives me "Simple User" in str instead of "Simple_User"

How we ca开发者_JS百科n do this???


You can do a friendly description like so:

public enum UserRole
    {
        [Description("Total administrator!!1!one")]
        Administrator = 1,

        [Description("This is a simple user")]
        Simple_User = 2,

        [Description("This is a paid user")]
        Paid_User = 3,
    }

And make a helper function:

 public static string GetDescription(Enum en)
        {
            Type type = en.GetType();

            MemberInfo[] info = type.GetMember(en.ToString());

            if (info != null && info.Length > 0)
            {
                object[] attrs = info[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (attrs != null && attrs.Length > 0)
                {
                    return ((DescriptionAttribute)attrs[0]).Description;
                }
            }

            return en.ToString();
        }

And use it like:

string description = GetDescription(UserRole.Administrator);


Okay so by now you know that enum really is a list of numbers that you can give a handy string handle to like:

public enum ErrorCode
{
    CTCLSM = 1,
    CTSTRPH = 2,
    FBR = 3,
    SNF = 4
}

Also, as @StriplingWarrior showed, you can go so far by getting the enum string name and replacing underscores etc. But what I think you want is a way of associating a nice human string with each value. How about this?

public enum ErrorCode
{
    [EnumDisplayName("Cataclysm")]
    CTCLSM = 1,
    [EnumDisplayName("Catastrophe")]
    CTSTRPH = 2,
    [EnumDisplayName("Fubar")]
    FBR = 3,
    [EnumDisplayName("Snafu")]
    SNF = 4
}

Okay there's probably something in System.ComponentModel that does this - let me know. The code for my solution is here:

[AttributeUsage(AttributeTargets.Field)]
public class EnumDisplayNameAttribute : System.Attribute
{
    public string DisplayName { get; set; }

    public EnumDisplayNameAttribute(string displayName)
    {
        DisplayName = displayName;
    }
}

And the funky Enum extension that makes it possible:

public static string PrettyFormat(this Enum enumValue)
{
    string text = enumValue.ToString();
    EnumDisplayNameAttribute displayName = (EnumDisplayNameAttribute)enumValue.GetType().GetField(text).GetCustomAttributes(typeof(EnumDisplayNameAttribute), false).SingleOrDefault();

    if (displayName != null)
        text = displayName.DisplayName;
    else
        text = text.PrettySpace().Capitalize(true);

    return text;
}

So to get the human-friendly value out you could just do ErrorCode.CTSTRPH.PrettyFormat()


Hmm, enums can't have string values. From MSDN's Enum page:

An enumeration is a set of named constants whose underlying type is any integral type except Char.


To get the string version of the enum use the Enum's ToString method.

String str = UserRole.Simple_User.ToString("F");


I'm a little confused by your question, because C# doesn't allow you to declare enums backed by strings. Do you mean that you want to get "Simple User", but you're getting "Simple_User" instead?

How about:

var str = UserRole.Simple_User.ToString().Replace("_", " ");


You can do this by attribute, but really I think using an enum like this is possibly the wrong way to go about things.

I would create a user role interface that exposes a display name property, then implement that interface with a new class for each role, this also let's you add more behaviour in the future. Or you could use an abstract class so any generic behaviour doesn't get duplicated...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜