我有以下场景
public class A
{
}
public class BA : A
{
}
//other subtypes of A are defined
public class AFactory
{
public T Create<T>() where T : A
{
//work to calculate condition
if (condition)
return new BA();
//return other subtype of A
}
}
Run Code Online (Sandbox Code Playgroud)
抛出以下编译错误:
错误CS0029无法将类型'B'隐式转换为'T'
怎么了?
好吧演员很容易失败.假设我有:
public class AB : A {}
B b = new B();
AB ab = b.Create<AB>();
Run Code Online (Sandbox Code Playgroud)
这最终会尝试为B类型变量分配引用AB.那些是不相容的.
听起来你可能不应该制作Create通用方法.或者,也许你应该让A通用:
public abstract class A<T> where T : A
{
public abstract T Create();
}
public class B : A<B>
{
public override B Create()
{
return new B();
}
}
Run Code Online (Sandbox Code Playgroud)
这可行 - 但我们不知道你想要实现什么,所以它实际上可能对你没有帮助.
或者,您可以保留当前的设计,但使用:
public T Create<T>() where T : A
{
return (T) (object) new B();
}
Run Code Online (Sandbox Code Playgroud)
如果你Create用类型参数调用除了之外的任何东西object,那将会失败,A或者B,这对我来说听起来有些奇怪......