为什么我在以下代码中遇到编译器错误:不能隐含地将类型 SpecialNode 转换为 T
,即使 T 必须从 NodeBase 派生,正如我在 where 子句中定义的那样,即使 SpecialNode 实际上是派生的来自 NodeBase?
public static T GetNode<T>() where T : NodeBase
{
if (typeof(T) == typeof(SpecialNode))
{
return ThisStaticClass.MySpecialNode; // <-- compiler error
}
if (typeof(T) == typeof(OtherSpecialNode))
{
return ThisStaticClass.MyOtherSpecialNode; // <-- compiler error
}
...
return default(T);
}
最佳答案
编译器不会读取您的 if
检查以意识到在这一特定行中,T
必须是 SpecialNode
。
你需要先转换到NodeBase
,像这样:
return (T)(NodeBase)MySpecialNode;
您需要进行强制转换,因为(就编译器所知)T
可能是 MyOtherSpecialNode
,并且您不能将 MyOtherSpecialNode
强制转换为 MySpecialNode
.
编辑:你可以像这样用一个类型转换来做:
NodeBase retVal;
if (typeof(T) == typeof(SpecialNode))
retVal = MySpecialNode;
else if (typeof(T) == typeof(OtherSpecialNode))
retVal = MyOtherSpecialNode;
return (T)retVal;
关于c# - 泛型方法中的隐式类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2765924/