相关疑难解决方法(0)

C#中的枚举类型约束

可能重复:
任何人都知道缺少枚举通用约束的好方法?

C#不允许对Enums 进行类型约束的原因是什么?我确信疯狂背后有一种方法,但我想明白为什么不可能.

以下是我希望能够做到的(理论上).

public static T GetEnum<T>(this string description) where T : Enum
{
...
}
Run Code Online (Sandbox Code Playgroud)

.net c# enums

149
推荐指数
4
解决办法
5万
查看次数

在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# ×2

enums ×2

.net ×1

casting ×1

generics ×1