相关疑难解决方法(0)

在C#中将Int转换为Generic Enum

类似于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)

c# generics enums casting

74
推荐指数
5
解决办法
3万
查看次数

C#将int类型的对象转换为可以为空的枚举

我只需要能够将一个对象转换为可以为空的枚举.对象可以是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)

c# enums nullable

17
推荐指数
2
解决办法
2万
查看次数

标签 统计

c# ×2

enums ×2

casting ×1

generics ×1

nullable ×1