这可能是一个新手问题,但谷歌出人意料地没有提供答案。
我有这种相当人为的方法
T HowToCast<T>(T t)
{
if (typeof(T) == typeof(string))
{
T newT1 = "some text";
T newT2 = (string)t;
}
return t;
}
来自C ++背景我希望这可以工作。但是,无法编译“无法将类型'T'隐式转换为字符串”和“无法将类型'T'转换为字符串”以进行上述两种分配。
我要么在概念上做错了,要么只是有错误的语法。请帮我整理一下。
谢谢!
即使它在if
块内,编译器也不知道T
是string
。
因此,它不会让你施展。 (出于同样的原因,你无法将DateTime
投射到string
)
你需要施放到object
,(任何T
都可以施放),然后从那里投射到string
(因为object
可以施放到string
)。
例如:
T newT1 = (T)(object)"some text";
string newT2 = (string)(object)t;
两条线都有同样的问题
T newT1 = "some text";
T newT2 = (string)t;
编译器不知道T是一个字符串,因此无法知道如何分配它。但既然你检查过你就可以强制它
T newT1 = "some text" as T;
T newT2 = t;
你不需要转换t因为它已经是一个字符串,所以还需要添加约束
where T : class
如果你要检查显式类型,为什么要将这些变量声明为T
?
T HowToCast<T>(T t)
{
if (typeof(T) == typeof(string))
{
var newT1 = "some text";
var newT2 = t; //this builds but I'm not sure what it does under the hood.
var newT3 = t.ToString(); //for sure the string you want.
}
return t;
}
如果您的类和方法都有通用声明,也会出现此错误。例如,下面显示的代码给出了此编译错误。
public class Foo <T> {
T var;
public <T> void doSomething(Class <T> cls) throws InstantiationException, IllegalAccessException {
this.var = cls.newInstance();
}
}
此代码编译(注意从方法声明中删除T):
public class Foo <T> {
T var;
public void doSomething(Class <T> cls) throws InstantiationException, IllegalAccessException {
this.var = cls.newInstance();
}
}
改变这一行:
if (typeof(T) == typeof(string))
对于这一行:
if (t.GetType() == typeof(string))