不,因为虽然C
继承自B
,A<C>
但不继承自A<B>
。
要理解为什么会这样,想象一下如果A<T>
是List<T>
:
class B { }
class C : B { }
class D : B { }
class My1 {
public My1(List<B> lessDerivedTemplateParameter)
{
// This is totally legal
lessDerivedTemplateParameter.Add(new D());
}
}
class My2 : My1 {
public My2(List<C> moreDerivedTemplateParameter)
// if this were allowed, then My1 could add a D to a list of Bs
: base(moreDerivedTemplateParameter)
{
}
}
另一方面,这是合法的:
interface IA<out T> {
public T GetSome();
}
class B { }
class C : B { }
class D : B { }
class My1 {
public My1(IA<B> lessDerivedTemplateParameter)
{
// This is totally legal
var someB = lessDerivedTemplateParameter.GetSome();
}
}
class My2 : My1 {
public My2(IA<C> moreDerivedTemplateParameter)
// This is allowed, because an A<C> only *produces* C's (which are also B's)
// so the base class (which consumes B's, and doesnt care if they are C's)
// can use an IA<C>
: base(moreDerivedTemplateParameter)
{
}
}