问题描述
以下团体为什么出错?
public interface IBase { }
public class ClassX : IBase
{
}
public class ClassY
{
public static ClassX FunctionReturnX() { return new ClassX(); }
}
public class ClassZ<TGeneric> where TGeneric : IBase
{
Func<IBase> funcInterface = ClassY.FunctionReturnX; //Right
Func<TGeneric> funcGeneric = ClassY.FunctionReturnX; //Wrong
}
推荐答案
您不能将 ClassX
强制转换为实现 IBase
的任何类。您只能保证能够将其强制转换为 IBase
本身。考虑下面的示例:
In summary, you cannot cast ClassX
to any class that implement IBase
. You are only guaranteed to be able to cast it to IBase
itself. Consider this example:
想象一下,您有一个实现 IBase的类
ClassA
。 code>像这样:
Imagine that you have a class ClassA
that implements IBase
like this:
public class ClassA : IBase
{
}
现在, ClassZ< ClassA>
看起来像这样(这不是真实的代码):
Now, ClassZ<ClassA>
would look like this (this is not real code):
public class ClassZ<ClassA>
{
Func<IBase> funcInterface = ClassY.FunctionReturnX; //Right
Func<ClassA> funcGeneric = ClassY.FunctionReturnX; //Wrong
}
ClassY.FunctionReturnX
返回 ClassX
,您可以将其强制转换为 IBase
,但不能将其强制转换为 A类
。因此,您会遇到并发症错误。
ClassY.FunctionReturnX
returns ClassX
which you can cast to IBase
, but you cannot cast it to ClassA
. Therefore, you get the complication error.
这篇关于为什么“ Func< IBase>”在'Func< TGeneric> TGeneric:IBase哪里没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!