在 C# 中将 Int 转换为通用枚举 [英] Cast Int to Generic Enum in C#

查看:50
本文介绍了在 C# 中将 Int 转换为通用枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于 C# 中将 int 转换为枚举 但我的枚举是通用类型参数.处理此问题的最佳方法是什么?

Similar to Cast int to enum in C# but my enum is a Generic Type parameter. What is the best way to handle this?

示例:

private T ConvertEnum<T>(int i) where T : struct, IConvertible
{
    return (T)i;
}

生成编译器错误无法将类型int"转换为T"

完整代码如下,其中value可以包含int,或者null.

Full code is as follows, where value can contain the int, or 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;
}

推荐答案

我发现的最简单的方法是通过向 object 添加强制转换来强制编译器的手.

The simplest way I have found is to force the compiler's hand by adding a cast to object.

return (T)(object)i.Value;

这篇关于在 C# 中将 Int 转换为通用枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆