枚举的字符串表示(estring)?

发布于 2024-10-15 08:44:05 字数 308 浏览 1 评论 0原文

我需要一个枚举或类似的东西来做这样的事情:

公共枚举MyStringEnum { [StringValue("Foo A")] Foo = "A", [StringValue("Foo B")] Foo = "B" }

这可能吗?我的示例,我返回一个数据集,其值表示为 A、B、C、D、E .. 我需要一个解决方案将其返回为字符串表示形式?

我想显而易见的是创建一个扩展方法或只有一个 switch 语句并返回一个字符串的东西..还有其他更干净的解决方案吗?

问候, 戴夫

i need an enum or something similiar to do something like this:

public enum MyStringEnum {
[StringValue("Foo A")] Foo = "A",
[StringValue("Foo B")] Foo = "B" }

is this possible? my example, i return back a dataset with a value represented as either A,B,C,D,E .. i need a solution to return this as a string representation?

i guess the obvious would be to create an extension method or something which just had a switch statement in and return a string .. any other cleaner solutions?

regards,
dave

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

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

发布评论

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

评论(5

幸福%小乖 2024-10-22 08:44:05

这是我们 MVC 应用程序用来检索枚举的显示名称的东西。它使用自定义属性和扩展方法来检索枚举显示名称。

[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class EnumDisplayNameAttribute : Attribute
{
  public EnumDisplayNameAttribute(string displayName)
  {
    DisplayName = displayName;
  }

  public string DisplayName { get; set; }
}


public static string GetDisplayName(this Enum enumType)
{
  var displayNameAttribute = enumType.GetType()
                                     .GetField(enumType.ToString())
                                     .GetCustomAttributes(typeof(EnumDisplayNameAttribute), false)
                                     .FirstOrDefault() as EnumDisplayNameAttribute;

  return displayNameAttribute != null ? displayNameAttribute.DisplayName : Enum.GetName(enumType.GetType(), enumType);
}

枚举的用法:

public enum Foo
{
  [EnumDisplayName("Foo Bar")]
  Bar = 0
}

获取显示名称:

var f = Foo.Bar;
var name =  f.GetDisplayName();

Here is something we use for our MVC applications to retrieve a display name for our enums. It uses a custom attribute and an extension method to retrieve the enum display name.

[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class EnumDisplayNameAttribute : Attribute
{
  public EnumDisplayNameAttribute(string displayName)
  {
    DisplayName = displayName;
  }

  public string DisplayName { get; set; }
}


public static string GetDisplayName(this Enum enumType)
{
  var displayNameAttribute = enumType.GetType()
                                     .GetField(enumType.ToString())
                                     .GetCustomAttributes(typeof(EnumDisplayNameAttribute), false)
                                     .FirstOrDefault() as EnumDisplayNameAttribute;

  return displayNameAttribute != null ? displayNameAttribute.DisplayName : Enum.GetName(enumType.GetType(), enumType);
}

Usage on the enum:

public enum Foo
{
  [EnumDisplayName("Foo Bar")]
  Bar = 0
}

Getting back the display name:

var f = Foo.Bar;
var name =  f.GetDisplayName();
扬花落满肩 2024-10-22 08:44:05

是否可以选择不使用枚举而使用结构?

struct FooEnum
{
    private int value;
    private string name;
    private FooEnum(int value, string name)
    {
        this.name = name;
        this.value = value;
    }

    public static readonly FooEnum A = new FooEnum(0, "Foo A");
    public static readonly FooEnum B = new FooEnum(1, "Foo B");
    public static readonly FooEnum C = new FooEnum(2, "Foo C");
    public static readonly FooEnum D = new FooEnum(3, "Foo D");

    public override string ToString()
    {
        return this.name;
    }

    //TODO explicit conversion to int etc.
}

然后,您可以像使用带有自己的 ToString() 重载的枚举一样使用 FooEnum:

FooEnum foo = FooEnum.A;
string s = foo.ToString(); //"Foo A"

Would it be an option not to use enum and use structs instead?

struct FooEnum
{
    private int value;
    private string name;
    private FooEnum(int value, string name)
    {
        this.name = name;
        this.value = value;
    }

    public static readonly FooEnum A = new FooEnum(0, "Foo A");
    public static readonly FooEnum B = new FooEnum(1, "Foo B");
    public static readonly FooEnum C = new FooEnum(2, "Foo C");
    public static readonly FooEnum D = new FooEnum(3, "Foo D");

    public override string ToString()
    {
        return this.name;
    }

    //TODO explicit conversion to int etc.
}

You could then use FooEnum like an enum with an own ToString() overload:

FooEnum foo = FooEnum.A;
string s = foo.ToString(); //"Foo A"
绝不放开 2024-10-22 08:44:05

如果你想做这样的事情:

MyStringEnum value = MyStringEnum.A;
string description = value.GetDescription();
// description == "Foo A"

像这样设置你的枚举:

public enum MyStringEnum
{
    [Description("Foo A")]
    A,
    [Description("Foo B")]
    B
}

并使用读取属性的实用程序/扩展方法:

public static string GetDescription(this MyStringEnum enumerationValue)
{
    Type type = enumerationValue.GetType();
    string name = enumerationValue.ToString();

    //Tries to find a DescriptionAttribute for a potential friendly name for the enum
    MemberInfo[] member = type.GetMember(name);
    if (member != null && member.Length > 0)
    {
        object[] attributes = member[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attributes != null && attributes.Length > 0)
        {
            //Pull out the description value
            return ((DescriptionAttribute)attributes[0]).Description;
        }
    }

    return name;
}

If you want to do something like this:

MyStringEnum value = MyStringEnum.A;
string description = value.GetDescription();
// description == "Foo A"

Setup your enum like this:

public enum MyStringEnum
{
    [Description("Foo A")]
    A,
    [Description("Foo B")]
    B
}

And use a utility/extension method that reads the attribute:

public static string GetDescription(this MyStringEnum enumerationValue)
{
    Type type = enumerationValue.GetType();
    string name = enumerationValue.ToString();

    //Tries to find a DescriptionAttribute for a potential friendly name for the enum
    MemberInfo[] member = type.GetMember(name);
    if (member != null && member.Length > 0)
    {
        object[] attributes = member[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attributes != null && attributes.Length > 0)
        {
            //Pull out the description value
            return ((DescriptionAttribute)attributes[0]).Description;
        }
    }

    return name;
}
指尖微凉心微凉 2024-10-22 08:44:05

我已经在我要放置的地方看到了这种情况

MyStringEnum.Foo.ToString();

在这种情况下它会给出“A”

I've seen this done where I would put

MyStringEnum.Foo.ToString();

In this case it would give "A"

池木 2024-10-22 08:44:05

解决此问题的最干净的解决方案是创建一个自定义属性,该属性将存储您想要的枚举常量的字符串值。我过去曾使用过该策略,效果相当好。这是一篇详细介绍所涉及工作的博客文章:

C# 中带有字符串值的枚举 - Stefan Sedich 的博客

当然,仅当您需要某种有意义的文本时才需要这样做。如果枚举常量的名称适合您...那么您只需调用 ToString() 即可。

The cleanest solution for this problem is to create a custom attribute that will store the string value you want for the enum constant. I've used that strategy in the past and it worked out fairly well. Here's a blog post detailing the work involved:

Enum With String Values In C# - Stefan Sedich's Blog

Of course this is only necessary if you need some kind of meaningful text. If the name of the enum constant works for you...then you can simply call ToString().

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