如何读取 ASP.Net 中的枚举值?

发布于 2024-11-25 05:13:48 字数 326 浏览 1 评论 0原文

我的枚举结构是这样的

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

现在我想通过使用它的名称来读取这个枚举值假设

String str = UserRole.Simple_User;

它在str中给我“Simple User”而不是“Simple_User”

我们怎么能做到这一点???

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 can do this???

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

你曾走过我的故事 2024-12-02 05:13:48

您可以像这样进行友好的描述:

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

并创建一个辅助函数:

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

并像这样使用它:

string description = GetDescription(UserRole.Administrator);

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);
在风中等你 2024-12-02 05:13:48

好吧,现在你知道枚举实际上是一个数字列表,你可以为它提供一个方便的字符串句柄:

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

另外,正如 @StriplingWarrior 所示,你可以通过获取枚举字符串名称并替换下划线等来走得更远。但是什么我认为你想要的是一种将一个好的人类字符串与每个值关联起来的方法。这个怎么样?

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

好吧,System.ComponentModel 中可能有一些东西可以做到这一点 - 让我知道。我的解决方案的代码在这里:

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

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

以及使之成为可能的时髦的 Enum 扩展:

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

因此,要获得人性化的值,您只需执行 ErrorCode.CTSTRPH.PrettyFormat()

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()

生死何惧 2024-12-02 05:13:48

嗯,枚举不能有字符串值。来自 MSDN 的 Enum 页面

枚举是一组命名常量,其基础类型是除 Char 之外的任何整型。


要获取枚举的字符串版本,请使用 Enum 的 ToString 方法。

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

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");
谈场末日恋爱 2024-12-02 05:13:48

我对你的问题有点困惑,因为 C# 不允许你声明由字符串支持的枚举。您的意思是您想要获得“Simple User”,但您得到的却是“Simple_User”?

怎么样:

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

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("_", " ");
诗酒趁年少 2024-12-02 05:13:48

您可以通过属性来做到这一点,但实际上我认为使用这样的枚举可能是错误的处理方式。

我将创建一个公开显示名称属性的用户角色接口,然后为每个角色使用一个新类来实现该接口,这也让您将来可以添加更多行为。
或者您可以使用抽象类,这样任何通用行为都不会重复......

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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文