类似于C#中的Cast int to enum,但我的枚举是Generic Type参数.处理这个问题的最佳方法是什么?
例:
private T ConvertEnum<T>(int i) where T : struct, IConvertible
{
return (T)i;
}
Run Code Online (Sandbox Code Playgroud)
生成编译器错误 Cannot convert type 'int' to 'T'
完整代码如下,其中value可以包含int或null.
private int? TryParseInt(string value)
{
var i = 0;
if (!int.TryParse(value, out i))
{
return null;
}
return i;
}
private T? TryParseEnum<T>(string value) where T : struct, IConvertible
{
var i = TryParseInt(value);
if (!i.HasValue)
{
return null;
}
return (T)i.Value;
}
Run Code Online (Sandbox Code Playgroud) 我只需要能够将一个对象转换为可以为空的枚举.对象可以是enum,null或int.谢谢!
public enum MyEnum { A, B }
void Put(object value)
{
System.Nullable<Myenum> val = (System.Nullable<MyEnum>)value;
}
Put(null); // works
Put(Myenum.B); // works
Put(1); // Invalid cast exception!!
Run Code Online (Sandbox Code Playgroud)