铸造诠释到通用枚举在C# [英] Cast Int to Generic Enum in C#

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

问题描述

类似演员的int枚举在C#中但我的枚举是一个泛型类型参数。什么是的的方式来处理这个



?例如:

 私人牛逼ConvertEnum< T>(int i)以其中T:结构,IConvertible 
{
回报率(T)I;
}



生成编译器错误无法键入'诠释'转换成'T'



全部代码如下,其中value可以包含int或空。

 私人诠释? TryParseInt(字符串值)
{
变种i = 0;
如果(int.TryParse(价值,走出我)!)
{
返回NULL;
}
回报我;
}

私人T' TryParseEnum< T>(字符串值)其中T:结构,IConvertible
{
变种I = TryParseInt(值);
如果
{
返回NULL(i.HasValue!);
}

回报率(T)i.Value;
}


解决方案

最简单的方法,我发现是通过将强制转换为对象来强制编译器的手。

 返回(T)(对象)i.Value; 


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

Example:

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

Generates compiler error Cannot convert type 'int' to 'T'

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;
}

解决方案

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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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