C# 如何检查字符串值是否在枚举列表中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10804102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:19:27  来源:igfitidea点击:

how to check if string value is in the Enum list?

c#c#-4.0c#-3.0

提问by qinking126

In my query string, I have an age variable ?age=New_Born.

在我的查询字符串中,我有一个年龄变量 ?age=New_Born

Is there a way I can check if this string value New_Bornis in my Enum list

有没有办法检查这个字符串值New_Born是否在我的枚举列表中

[Flags]
public enum Age
{
    New_Born = 1,
    Toddler = 2,
    Preschool = 4,
    Kindergarten = 8
}

I could use if statement for right now, but if my Enum list gets bigger. I want to find a better way to do it. I am thinking about to use Linq, just not sure how to do it.

我现在可以使用 if 语句,但如果我的 Enum 列表变大。我想找到一种更好的方法来做到这一点。我正在考虑使用 Linq,只是不知道该怎么做。

采纳答案by AaronS

You can use:

您可以使用:

 Enum.IsDefined(typeof(Age), youragevariable)

回答by agent-j

To parse the age:

解析年龄:

Age age;
if (Enum.TryParse(typeof(Age), "New_Born", out age))
  MessageBox.Show("Defined");  // Defined for "New_Born, 1, 4 , 8, 12"

To see if it is defined:

查看是否定义:

if (Enum.IsDefined(typeof(Age), "New_Born"))
   MessageBox.Show("Defined");

Depending on how you plan to use the Ageenum, flagsmay not be the right thing. As you probably know, [Flags]indicates you want to allow multiple values (as in a bit mask). IsDefinedwill return false for Age.Toddler | Age.Preschoolbecause it has multiple values.

根据您计划如何使用Age枚举,标志可能不是正确的事情。您可能知道,[Flags]表示您希望允许多个值(如位掩码)。 IsDefined将返回 falseAge.Toddler | Age.Preschool因为它有多个值。

回答by Omar

You can use the TryParsemethod that returns true if it successful:

如果成功,您可以使用返回 true的TryParse方法:

Age age;

if(Enum.TryParse<Age>("myString", out age))
{
   //Here you can use age
}

回答by John Koerner

You can use the Enum.TryParse method:

您可以使用 Enum.TryParse 方法:

Age age;
if (Enum.TryParse<Age>("New_Born", out age))
{
    // You now have the value in age 
}

回答by Viacheslav Smityukh

You should use Enum.TryParse to achive your goal

你应该使用 Enum.TryParse 来实现你的目标

This is a example:

这是一个例子:

[Flags]
private enum TestEnum
{
    Value1 = 1,
    Value2 = 2
}

static void Main(string[] args)
{
    var enumName = "Value1";
    TestEnum enumValue;

    if (!TestEnum.TryParse(enumName, out enumValue))
    {
        throw new Exception("Wrong enum value");
    }

    // enumValue contains parsed value
}

回答by jwsadler

I know this is an old thread, but here's a slightly different approach using attributes on the Enumerates and then a helper class to find the enumerate that matches.

我知道这是一个旧线程,但这里有一种稍微不同的方法,它使用枚举上的属性,然后使用帮助类来查找匹配的枚举。

This way you could have multiple mappings on a single enumerate.

这样你就可以在一个枚举上有多个映射。

public enum Age
{
    [Metadata("Value", "New_Born")]
    [Metadata("Value", "NewBorn")]
    New_Born = 1,
    [Metadata("Value", "Toddler")]
    Toddler = 2,
    [Metadata("Value", "Preschool")]
    Preschool = 4,
    [Metadata("Value", "Kindergarten")]
    Kindergarten = 8
}

With my helper class like this

和我这样的帮手班

public static class MetadataHelper
{
    public static string GetFirstValueFromMetaDataAttribute<T>(this T value, string metaDataDescription)
    {
        return GetValueFromMetaDataAttribute(value, metaDataDescription).FirstOrDefault();
    }

    private static IEnumerable<string> GetValueFromMetaDataAttribute<T>(T value, string metaDataDescription)
    {
        var attribs =
            value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof (MetadataAttribute), true);
        return attribs.Any()
            ? (from p in (MetadataAttribute[]) attribs
                where p.Description.ToLower() == metaDataDescription.ToLower()
                select p.MetaData).ToList()
            : new List<string>();
    }

    public static List<T> GetEnumeratesByMetaData<T>(string metadataDescription, string value)
    {
        return
            typeof (T).GetEnumValues().Cast<T>().Where(
                enumerate =>
                    GetValueFromMetaDataAttribute(enumerate, metadataDescription).Any(
                        p => p.ToLower() == value.ToLower())).ToList();
    }

    public static List<T> GetNotEnumeratesByMetaData<T>(string metadataDescription, string value)
    {
        return
            typeof (T).GetEnumValues().Cast<T>().Where(
                enumerate =>
                    GetValueFromMetaDataAttribute(enumerate, metadataDescription).All(
                        p => p.ToLower() != value.ToLower())).ToList();
    }

}

you can then do something like

然后你可以做类似的事情

var enumerates = MetadataHelper.GetEnumeratesByMetaData<Age>("Value", "New_Born");

And for completeness here is the attribute:

为了完整起见,这里是属性:

 [AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = true)]
public class MetadataAttribute : Attribute
{
    public MetadataAttribute(string description, string metaData = "")
    {
        Description = description;
        MetaData = metaData;
    }

    public string Description { get; set; }
    public string MetaData { get; set; }
}

回答by Andy

I've got a handy extension method that uses TryParse, as IsDefined is case-sensitive.

我有一个使用 TryParse 的方便的扩展方法,因为 IsDefined 区分大小写。

public static bool IsParsable<T>(this string value) where T : struct
{
    return Enum.TryParse<T>(value, true, out _);
}