如何将字符串值分配给枚举并在开关中使用该值

发布于 2024-12-12 18:47:24 字数 234 浏览 0 评论 0 原文

基本上,一系列标题将被传递到 switch 语句中,我需要将它们与枚举的字符串值进行比较。但我几乎不知道如何正确地做到这一点。

另外,我不知道这是否是最好的方法,所以是否有人有任何想法?

例如:

enum
{
    doctor = "doctor",
    mr = "mr",
    mrs = "mrs"
}

然后切换我分配给它们的字符串值。

Basically a series of titles will be passed into the switch statement and I need to compare them against the string values of the enum. But I have little to no idea how to do this correctly.

Also, I don't know if this is even the best approach so if anyone has any ideas?

For example:

enum
{
    doctor = "doctor",
    mr = "mr",
    mrs = "mrs"
}

and then switch through the string values I've assigned them.

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

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

发布评论

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

评论(11

長街聽風 2024-12-19 18:47:24

我发现执行此操作的最佳方法是在枚举值上使用 System.ComponentModel.DescriptionAttribute 属性。

下面是一个示例:

using System.ComponentModel;

public enum ActionCode
{
    [Description("E")]
    Edit,
    [Description("D")]
    Delete,
    [Description("R")]
    Restore
}

然后,要使用它,请在静态类上创建一个扩展方法,如下所示:

编辑:我重写了该方法以包含 Laurie Dickinson 的一个很好的建议,以便该方法返回枚举值的名称当没有描述属性时。我还重构了该方法以尝试改进功能。现在,它适用于所有枚举,而无需使用 IConvertible

public static class Extensions
{
    public static string GetDescription(this Enum e)
    {
        var attribute =
            e.GetType()
                .GetTypeInfo()
                .GetMember(e.ToString())
                .FirstOrDefault(member => member.MemberType == MemberTypes.Field)
                .GetCustomAttributes(typeof(DescriptionAttribute), false)
                .SingleOrDefault()
                as DescriptionAttribute;

        return attribute?.Description ?? e.ToString();
    }
}

因此,要获取与上面的枚举关联的字符串,我们可以使用以下代码:

using Your.Extension.Method.Namespace;

...

var action = ActionCode.Edit;
var actionDescription = action.GetDescription();

// Value of actionDescription will be "E".

这是另一个示例枚举:

public enum TestEnum
{
    [Description("This is test 1")]
    Test1,
    Test2,
    [Description("This is test 3")]
    Test3

}

这是代码查看描述:

var test = TestEnum.Test2;
var testDescription = test.GetDescription();
test = TestEnum.Test3;
var testDescription2 = test.GetDescription();

结果将是:

testDescription: "Test2"
testDescription2: "This is test 3"

我想继续发布通用方法,因为它更有用。它使您不必为所有枚举编写自定义扩展。

I found that the best way for me to do this is by using the System.ComponentModel.DescriptionAttribute attribute on the enum values.

Here is an example:

using System.ComponentModel;

public enum ActionCode
{
    [Description("E")]
    Edit,
    [Description("D")]
    Delete,
    [Description("R")]
    Restore
}

Then, to use it, create an extension method on a static class like so:

Edit: I rewrote the method to include a great suggestion from Laurie Dickinson so that the method returns the name of the enum value when there is no Description attribute. I also refactored the method to try to improve functionality. It now works for all Enums without using IConvertible.

public static class Extensions
{
    public static string GetDescription(this Enum e)
    {
        var attribute =
            e.GetType()
                .GetTypeInfo()
                .GetMember(e.ToString())
                .FirstOrDefault(member => member.MemberType == MemberTypes.Field)
                .GetCustomAttributes(typeof(DescriptionAttribute), false)
                .SingleOrDefault()
                as DescriptionAttribute;

        return attribute?.Description ?? e.ToString();
    }
}

So, to get the string associated with our enum above, we could use the following code:

using Your.Extension.Method.Namespace;

...

var action = ActionCode.Edit;
var actionDescription = action.GetDescription();

// Value of actionDescription will be "E".

Here is another sample Enum:

public enum TestEnum
{
    [Description("This is test 1")]
    Test1,
    Test2,
    [Description("This is test 3")]
    Test3

}

Here is the code to see the description:

var test = TestEnum.Test2;
var testDescription = test.GetDescription();
test = TestEnum.Test3;
var testDescription2 = test.GetDescription();

Results will be:

testDescription: "Test2"
testDescription2: "This is test 3"

I wanted to go ahead and post the generic method as it is much more useful. It prevents you from having to write a custom extension for all of your enums.

天涯沦落人 2024-12-19 18:47:24

您不能使用 enum string 的基础类型。 基础类型可以是除 char 之外的任何整数类型

如果您想将字符串转换为枚举,那么您可能需要使用解析TryParse 方法。

string incoming = "doctor";

// throws an exception if the string can't be parsed as a TestEnum
TestEnum foo = (TestEnum)Enum.Parse(typeof(TestEnum), incoming, true);

// try to parse the string as a TestEnum without throwing an exception
TestEnum bar;
if (Enum.TryParse(incoming, true, out bar))
{
    // success
}
else
{
    // the string isn't an element of TestEnum
}

// ...

enum TestEnum
{
    Doctor, Mr, Mrs
}

You can't have an enum with an underlying type of string. The underlying type can be any integral type except char.

If you want to translate a string to your enum then you'll probably need to use the Parse or TryParse methods.

string incoming = "doctor";

// throws an exception if the string can't be parsed as a TestEnum
TestEnum foo = (TestEnum)Enum.Parse(typeof(TestEnum), incoming, true);

// try to parse the string as a TestEnum without throwing an exception
TestEnum bar;
if (Enum.TryParse(incoming, true, out bar))
{
    // success
}
else
{
    // the string isn't an element of TestEnum
}

// ...

enum TestEnum
{
    Doctor, Mr, Mrs
}
左秋 2024-12-19 18:47:24

Enum 只能具有整型基础类型(char 除外)。因此你不能做你想做的事,至少不能直接做。

但是,您可以将字符串转换为枚举类型:

EnumType eVal = (EnumType)Enum.Parse(typeof(EnumType), strValue);

switch(eVal)
{
    case EnumType.doctor:/*...*/; break;
    case EnumType.mr: /*...*/; break;
}

Enum can only have integral underlying types (except char). Therefore you cannot do what you want, at least directly.

However you can translate the string you have to the enum type:

EnumType eVal = (EnumType)Enum.Parse(typeof(EnumType), strValue);

switch(eVal)
{
    case EnumType.doctor:/*...*/; break;
    case EnumType.mr: /*...*/; break;
}
七婞 2024-12-19 18:47:24

我相信执行此操作的标准方法是使用具有只读字符串属性的静态类,该属性返回您想要的值。

I believe the standard way to do this is to use a static class with readonly string properties that return the value you want.

极度宠爱 2024-12-19 18:47:24

我想为使用 C# 6 或更高版本的任何人添加另一个答案。

如果您只想获取 Enum 值的名称,可以使用 C# 6 中引入的新 nameof() 方法。

string enumName = nameof(MyEnum.EnumVal1); // enumName will equal "EnumVal1"

虽然乍一看这似乎有些过分(为什么不直接将字符串的值设置为“EnumVal1”) " 首先?),它会给你编译时检查以确保该值有效。因此,如果您更改了枚举值的名称,并且忘记告诉您的 IDE 查找并替换所有引用,则在您修复它们之前它不会编译。

I wanted to add another answer for anyone using C# 6 or greater.

If you are only wanting to get the name of the Enum value, you could use the new nameof() method introduced in C# 6.

string enumName = nameof(MyEnum.EnumVal1); // enumName will equal "EnumVal1"

While this may seem like overkill at first glance (why not just set the value of the string to "EnumVal1" to start with?), it will give you compile-time checking to make sure the value is valid. So, if you ever change the name of the enum value and forget to tell your IDE to find and replace all references, it will not compile until you fix them.

梦与时光遇 2024-12-19 18:47:24

这不应该是硬编码的事情。它应该是数据驱动的,可能从外部文件或数据库读取。您可以将它们存储在字典中,并使用按键来驱动您的逻辑。

This is not the kind of thing that should be hard-coded. It should be data-driven, possibly read from an external file or database. You could store them in a Dictionary and use the keys to drive your logic.

只有一腔孤勇 2024-12-19 18:47:24

枚举不能是字符串类型。

批准的枚举类型为 byte、sbyte、short、ushort、int、uint、long 或 ulong。

http://msdn.microsoft.com/en-us/library/sbbt4032.aspx

Enumerations cannot be of string type.

The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.

http://msdn.microsoft.com/en-us/library/sbbt4032.aspx

陌上芳菲 2024-12-19 18:47:24

为什么不只使用纯枚举和开关?

enum Prefix
{
    doctor,
    mr,
    mrs
}

然后你可以使用就像

string case = "doctor";

switch ((Prefix)Enum.Parse(typeof(Prefix), "doctor"))
{
    case Prefix.doctor:
        ...
        break;
    ...
    default:
        break;
}

Why not to use just pure enum and switches?

enum Prefix
{
    doctor,
    mr,
    mrs
}

Then you can use is like

string case = "doctor";

switch ((Prefix)Enum.Parse(typeof(Prefix), "doctor"))
{
    case Prefix.doctor:
        ...
        break;
    ...
    default:
        break;
}
风筝有风,海豚有海 2024-12-19 18:47:24

只是分享我的解决方案。通过下载 nuget 包 Extension.MV,可以使用一种方法从枚举描述中获取字符串

public enum Prefix
{
    [Description("doctor")]
    doctor = 1,
    [Description("mr")]
    mr = 2,
    [Description("mrs")]
    mrs = 3
}

public static class PrefixAdapter {

    public static string ToText(this Prefix prefix) {
        return prefix.GetEnumDescription();
    }

    public static Prefix ToPrefix(this string text) {
        switch (text)
        {
            case "doctor"
                return Prefix.doctor;
            case "mr"
                return Prefix.mr;
            case "ms"
                return Prefix.mrs;
        }
    }
}

Just sharing my solution. By downloading the nuget package Extension.MV, a method is available for getting the string from a Enum Description

public enum Prefix
{
    [Description("doctor")]
    doctor = 1,
    [Description("mr")]
    mr = 2,
    [Description("mrs")]
    mrs = 3
}

public static class PrefixAdapter {

    public static string ToText(this Prefix prefix) {
        return prefix.GetEnumDescription();
    }

    public static Prefix ToPrefix(this string text) {
        switch (text)
        {
            case "doctor"
                return Prefix.doctor;
            case "mr"
                return Prefix.mr;
            case "ms"
                return Prefix.mrs;
        }
    }
}
笔芯 2024-12-19 18:47:24

如果你真的是 c# 8 的硬核......

public static string GetDescription(this VendorContactType enumval) =>
        enumval switch {
            VendorContactType.AccountContact => "Account Contact",
            VendorContactType.OrderContact => "Order Contact",
            VendorContactType.OrderContactCC => "Order Contact CC",
            VendorContactType.QualityContact => "Quality Contact",
            VendorContactType.ShippingContact => "Shipping Contact",
            _ => ""
        };

我意识到这不会接受你程序的所有枚举,但这是我使用的并且我喜欢它。

If you're really hardcore and on c# 8...

public static string GetDescription(this VendorContactType enumval) =>
        enumval switch {
            VendorContactType.AccountContact => "Account Contact",
            VendorContactType.OrderContact => "Order Contact",
            VendorContactType.OrderContactCC => "Order Contact CC",
            VendorContactType.QualityContact => "Quality Contact",
            VendorContactType.ShippingContact => "Shipping Contact",
            _ => ""
        };

I realize this won't accept all of your program's enums but it's what I use and I like it.

羁〃客ぐ 2024-12-19 18:47:24

阅读本教程来了解枚举的工作原理。还有 switch 语句的示例。

Have a read of this tutorial to understand how enums work. There are examples of switch statements too.

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