这可能是一个新手的问题,但谷歌出人意料地没有提供答案.
我有这种相当人为的方法
T HowToCast<T>(T t)
{
if (typeof(T) == typeof(string))
{
T newT1 = "some text";
T newT2 = (string)t;
}
return t;
}
Run Code Online (Sandbox Code Playgroud)
来自C++背景我希望这可以工作.但是,无法编译"无法将类型'T'隐式转换为字符串"和"无法将类型'T'转换为字符串"以进行上述两种分配.
我要么在概念上做错了,要么只是有错误的语法.请帮我整理一下.
谢谢!
当我在我的代码中尝试调用此函数时,我在标题中得到错误.运算符'+ ='也不能应用于'int'和'T'类型的操作数
public int Change<T>(Stats type, T value)
{
Dictionary<string, string> temp = new Dictionary<string, string>();
temp = sql.Query(string.Format("SELECT {0} FROM player WHERE fbId='{1}'", type.ToString(), FBId));
if (typeof(T) == typeof(int))
{
int t = Convert.ToInt16(temp[type.ToString()]);
t += value;
if (t < 0) return -1;
PlayerStats[type] = t;
}
sql.Upload(string.Format("UPDATE player SET {0}='{1}' WHERE fbId='{2}'", type.ToString(), PlayerStats[type], FBId));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我用以下方法调用该函数:
Change<int>(type, 1);
Run Code Online (Sandbox Code Playgroud)