无法将类型“Int"隐式转换为“T" [英] Cannot implicitly convert type 'Int' to 'T'

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

问题描述

我可以调用 Get(Stat);Get(Name);

但是在编译时我得到:

不能将类型 'int' 隐式转换为 'T'

Cannot implicitly convert type 'int' to 'T'

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.

如果 T 只能是 int 或 string,那么首先不要以这种方式编写代码.编写两种方法,一种返回整数,一种返回字符串.

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.

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

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