6

我正在阅读一些关于通用方差的内容,但我还没有完全理解它,但我想知道它是否使以下内容成为可能?

class A<T> { }

class B { }

class C : B { }

class My1  {
    public My1(A<B> lessDerivedTemplateParameter)
    {
    }
}

class My2 : My1 {
    public My2(A<C> moreDerivedTemplateParameter)
        : base(moreDerivedTemplateParameter) // <-- compile error here, cannot convert
    {
    }
}
4

2 回答 2

6

不,因为虽然C继承自BA<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)
    {
    }
}
于 2012-05-25T19:17:53.720 回答
2

您可以将 A 声明为具有逆变类型参数的接口,它将编译:

internal interface A<out T>
    {
    }

    internal class B
    {
    }

    internal class C : B
    {
    }

    internal class My1
    {
    public My1(A<B> lessDerivedTemplateParameter)
    {
    }
}

internal class My2 : My1
{
    public My2(A<C> moreDerivedTemplateParameter)
        : base(moreDerivedTemplateParameter) 
    {
    }

}
于 2012-05-25T19:26:49.960 回答