且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法隐式转换类型'诠释'到'T'

更新时间:2022-10-23 15:50:53

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



如果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.