我正在尝试构建从用户字符串获取的泛型函数,并尝试将其解析为Enum valuse,如下所示:
private Enum getEnumStringEnumType(Type i_EnumType)
{
string userInputString = string.Empty;
Enum resultInputType;
bool enumParseResult = false;
while (!enumParseResult)
{
userInputString = System.Console.ReadLine();
enumParseResult = Enum.TryParse(userInputString, true, out resultInputType);
}
}
但我得到了:
The type 'System.Enum' must be a non-nullable value type in order to use it as parameter 'TEnum' in the generic type or method 'System.Enum.TryParse<TEnum>(string, bool, out TEnum) .
该错误意味着我需要为resultInputType的特定枚举取消引用?我该如何解决这个问题呢?谢谢。
发布于 2012-05-21 21:08:47
您应该创建一个泛型方法:
private T getEnumStringEnumType<T>() where T : struct, IConvertible
{
string userInputString = string.Empty;
T resultInputType = default(T);
bool enumParseResult = false;
while (!enumParseResult)
{
userInputString = System.Console.ReadLine();
enumParseResult = Enum.TryParse<T>(userInputString, out resultInputType);
}
return resultInputType;
}
用法:
public enum myEnum { val1, val2 }
myEnum enumValue = getEnumStringEnumType<myEnum>();
发布于 2019-05-22 15:18:46
字符串扩展方法
public TEnum ToEnum<TEnum>(this string value, TEnum defaultValue){
if (string.IsNullOrEmpty(value))return defaultValue;
return Enum.Parse(typeof(TEnum), value, true);}
https://stackoverflow.com/questions/10685794
复制相似问题