无法隐式转换类型'诠释'到'T' [英] Cannot implicitly convert type 'Int' to 'T'

查看:126
本文介绍了无法隐式转换类型'诠释'到'T'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以叫获取LT; INT>(STAT); 获取LT;串>(名称);



但编译我得到无法隐式转换type'int'到'T'和字符串同样的事情时

 公开吨得到< T>(统计型),其中T:IConvertible 
{
如果(typeof运算(T)== typeof运算(INT))
{
INT T = Convert.ToInt16(PlayerStats [类型]);
返回吨;
}
如果(typeof运算(T)== typeof运算(字符串))
{
串T = PlayerStats [类型]的ToString();
返回吨;
}
}


解决方案

任何你发现自己在一个型开关通用的你几乎可以肯定做错了什么的时间。仿制药应的通用的;他们应该操作相同的完全独立的类型



如果T只能是int或字符串,然后不写代码这种方式在所有摆在首位。 写两种方法,一种是返回一个int和一个返回一个字符串。


I can call Get<int>(Stat); or Get<string>(Name);

But when compiling i get Cannot implicitly convert type'int' to 'T' and the same thing for string

public T Get<T>(Stats type ) where T : IConvertible
{
    if (typeof(T) == typeof(int))
    {
        int t = Convert.ToInt16(PlayerStats[type]);
        return t;
    }
    if (typeof(T) == typeof(string))
    {
        string t = PlayerStats[type].ToString();
        return t;
    }
}

解决方案

Any time you find yourself switching on a type in a generic you are almost certainly doing something wrong. Generics should be generic; they should operate identically completely independent of the type.

If T can only be int or string then don't write your code this way at all in the first place. Write two methods, one that returns an int and one that returns a string.

这篇关于无法隐式转换类型'诠释'到'T'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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