类型“ T”的值不能转换为 [英] Value of type 'T' cannot be converted to
问题描述
这可能是一个新手问题,但是Google出人意料地没有提供答案。
This is likely a a novice question, but google surprisingly did not provide an answer.
我有这种相当人为的方法
I have this rather artificial method
T HowToCast<T>(T t)
{
if (typeof(T) == typeof(string))
{
T newT1 = "some text";
T newT2 = (string)t;
}
return t;
}
来自C ++背景,我期望它能起作用。但是,对于上述两个分配,它都无法通过不能将类型'T'隐式转换为字符串和不能将类型'T'转换为字符串进行编译。
Coming from a C++ background I have expected this to work. However, it fails to compile with "Cannot implicitly convert type 'T' to string" and "Cannot convert type 'T' to string" for both of the above assignments.
我在概念上做错了或者语法错误。
I am either doing something conceptually wrong or just have the wrong syntax. Please help me sort this one out.
谢谢!
推荐答案
即使位于 if
块中,编译器也不知道 T
是 string
。
因此,它不允许您进行投射。 (出于同样的原因,您不能将 DateTime
转换为 string
)
Even though it's inside of an if
block, the compiler doesn't know that T
is string
.
Therefore, it doesn't let you cast. (For the same reason that you cannot cast DateTime
to string
)
您需要转换为对象
(任何 T
都可以转换为对象),然后从那里转换为 string
(因为 object
可以强制转换为 string
)。
例如:
You need to cast to object
, (which any T
can cast to), and from there to string
(since object
can be cast to string
).
For example:
T newT1 = (T)(object)"some text";
string newT2 = (string)(object)t;
这篇关于类型“ T”的值不能转换为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!