C# 如何检查字符串值是否在枚举列表中?
在我的查询字符串中,我有一个年龄变量C# 如何检查字符串值是否在枚举列表中?,c#,c#-4.0,c#-3.0,C#,C# 4.0,C# 3.0,在我的查询字符串中,我有一个年龄变量?age=New\u Born 是否有办法检查此字符串值New_Born是否在我的枚举列表中 [Flags] public enum Age { New_Born = 1, Toddler = 2, Preschool = 4, Kindergarten = 8 } 我现在可以使用if语句,但如果我的枚举列表变大了。我想找到一个更好的方法。我正在考虑使用Linq,只是不确定如何使用。您可以使用: Enum.IsDefined
?age=New\u Born
是否有办法检查此字符串值New_Born
是否在我的枚举列表中
[Flags]
public enum Age
{
New_Born = 1,
Toddler = 2,
Preschool = 4,
Kindergarten = 8
}
我现在可以使用if语句,但如果我的枚举列表变大了。我想找到一个更好的方法。我正在考虑使用Linq,只是不确定如何使用。您可以使用:
Enum.IsDefined(typeof(Age), youragevariable)
要分析年龄,请执行以下操作:
Age age;
if (Enum.TryParse(typeof(Age), "New_Born", out age))
MessageBox.Show("Defined"); // Defined for "New_Born, 1, 4 , 8, 12"
要查看它是否已定义,请执行以下操作:
if (Enum.IsDefined(typeof(Age), "New_Born"))
MessageBox.Show("Defined");
根据您计划如何使用Age
enum,标志可能不是正确的选择。您可能知道,[Flags]
表示您希望允许多个值(如在位掩码中)IsDefined
对于Age.jackbird | Age.prefort
将返回false,因为它有多个值。如果成功,可以使用返回true的方法:
Age age;
if(Enum.TryParse<Age>("myString", out age))
{
//Here you can use age
}
年龄;
if(Enum.TryParse(“myString”,out age))
{
//在这里你可以使用年龄
}
您可以使用Enum.TryParse方法:
Age age;
if (Enum.TryParse<Age>("New_Born", out age))
{
// You now have the value in age
}
年龄;
if(特瑞帕斯(出生于外的新年龄))
{
//你现在有了年龄的价值
}
您应该使用Enum.TryParse来实现您的目标
这是一个例子:
[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
}
我知道这是一个旧线程,但这里有一个稍微不同的方法,使用枚举上的属性,然后使用帮助器类来查找匹配的枚举 这样,您可以在一个枚举上有多个映射
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
}
我的助手类是这样的
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();
}
}
我有一个方便的扩展方法,它使用TryParse,因为它定义为区分大小写
public static bool IsParsable<T>(this string value) where T : struct
{
return Enum.TryParse<T>(value, true, out _);
}
publicstaticboolisparsable(此字符串值),其中T:struct
{
返回Enum.TryParse(值,true,out u2;);
}
Enum.IsDefined
不正常?应使用,因为它是未经验证的输入。MessageBox在web环境中没有实际意义。IsDefined要求Enum实例选中记住Enum.IsDefined()
区分大小写!所以这不是一个“通用解决方案”。通常建议不要使用IsDefined,因为Is使用反射,调用IsDefined在性能和CPU方面是非常昂贵的。改用胰蛋白酶。(从pluralsight.com了解到)这只适用于.NET 4。问题是,如果提供任何整数(而不是“New_Born”字符串),它将返回true。
[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; }
}
public static bool IsParsable<T>(this string value) where T : struct
{
return Enum.TryParse<T>(value, true, out _);
}