[英]Return default Enum value when Enum type is not known
I have a method that attempts to match string to DescriptionAttribute of enum values and then return the enum value.我有一个方法尝试将字符串与枚举值的 DescriptionAttribute 匹配,然后返回枚举值。 In case a match is not found, it should return a default value, which I thought I could just return 0. But it's not going to happen...
如果找不到匹配项,它应该返回一个默认值,我以为我可以只返回 0。但它不会发生......
private Enum GetEnumFromDescription(Type enumType, string description)
{
var enumValues = Enum.GetValues(enumType);
foreach (Enum e in enumValues)
{
if (string.Compare(description, GetDescription(e), true) == 0)
return e;
}
return 0; // not compiling
}
How should I code the above?我应该如何编码上述内容?
You can use您可以使用
return (Enum) Activator.CreateInstance(enumType);
This will give you the default value for the type - which is what you want.这将为您提供类型的默认值 - 这就是您想要的。
EDIT: I'd expected that you'd know the type at compile time, in which case generics are a good approach.编辑:我希望你在编译时知道类型,在这种情况下泛型是一个很好的方法。 Even though that appears not to be the case, I'll leave the rest of this answer in case it's of any use to someone else.
即使情况似乎并非如此,我还是会留下这个答案的其余部分,以防对其他人有用。
Alternatively, you could use Unconstrained Melody which already contains something like this functionality in a more efficient, type-safe form :)或者,您可以使用Unconstrained Melody ,它已经以更高效、类型安全的形式包含了类似的功能:)
MyEnum value;
if (Enums.TryParseDescription<MyEnum>(description, out value))
{
// Parse successful
}
value
will be set to the "0" value if the parse operation isn't successful.如果解析操作不成功,
value
将设置为“0”值。
Currently it's case-sensitive, but you could easily create a case-insensitive version.目前它区分大小写,但您可以轻松创建不区分大小写的版本。 (Or let me know and I can do so.)
(或者让我知道,我可以这样做。)
I believe that the correct approach is我相信正确的方法是
(Enum)Enum.ToObject(enumType, 0)
Because因为
Activator.CreateInstance
is generic solution for all value types and Enum.ToObject
is a specific solution for enums, so Enum.ToObject
declares clear intentions of the code. Activator.CreateInstance
是所有值类型的通用解决方案, Enum.ToObject
是枚举的特定解决方案,因此Enum.ToObject
声明了代码的明确意图。Enum.ToObject
probably works faster than Activator.CreateInstance
Enum.ToObject
可能比Activator.CreateInstance
工作得更快Enum.ToObject
is used inside Enum.GetValues
to retrieve values. Enum.ToObject
在Enum.GetValues
用于检索值。default(T) will work for this. default(T) 将为此工作。 Get the type and use default.
获取类型并使用默认值。 By default first element will be taken as Default value
默认情况下,第一个元素将被视为默认值
也许这会奏效
return (Enum)enumValues[0];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.