将值解析为可为空的枚举 [英] Parsing value into nullable enumeration
问题描述
比方说我有这个:
PriorityType? priority;
string userInput = ...;
我无法更改其定义方式: PriorityType?优先级
,因为它实际上是与另一段代码的合同的一部分.
I cannot change how this is defined: PriorityType? priority
because it's actually part of a contract with another piece of code.
我尝试过此方法,但是它不起作用:
I tried this, but it does not work:
if (Enum.TryParse<PriorityType?>(userInput, out priority)) {
正确的方法是什么?
推荐答案
最简单的方法:
PriorityType tempPriority;
PriorityType? priority;
if (Enum.TryParse<PriorityType>(userInput, out tempPriority))
priority = tempPriority;
这是我能想到的最好的方法
This is the best I can come up with:
public static class NullableEnum
{
public static bool TryParse<T>(string value, out T? result) where T :struct, IConvertible
{
if (!typeof(T).IsEnum)
throw new Exception("This method is only for Enums");
T tempResult = default(T);
if (Enum.TryParse<T>(value, out tempResult))
{
result = tempResult;
return true;
}
result = null;
return false;
}
}
使用:
if (NullableEnum.TryParse<PriorityType>(userInput, out priority))
上面的类可以像 Enum.TryParse
一样使用,除了输入可以为空.您可以添加另一个采用不可为空的 T
的重载函数,以便您可以根据需要在两个实例中使用它.不幸的是,扩展方法在枚举类型上不能很好地工作(据我所知,我可以在很短的时间内尝试对其进行操作).
The above class can be used just like Enum.TryParse
except with a nullable input. You could add another overloaded function that takes a non-nullable T
so that you could use it in both instances if you want. Unfortunately extension methods don't work very well on enum types (as far as I could try to manipulate it in the short time I tried).
这篇关于将值解析为可为空的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!