C#泛型类中的协方差

Bop*_*Bop 3 c# covariance c#-4.0 .net-4.5

C#4.0 .NET 4.5 Silverlight 5我似乎无法找到解决方案,所以需要一些帮助.

我有基类Base和派生类Child:Base.我还有一个helper类,它具有泛型类型来执行特定的工作,一个EF实体Helper,其中T:EntityObject.

Child使用特定实体MyEntity:EntityObject执行特定工作.

所以我尝试过:

public class Base
{
    protected Helper<EntityObject> helper;
}
public class Child : Base
{
    public Child()
    {
        helper = new Helper<MyEntity>();
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望更多的派生类必须知道更具体的泛型参数,我认为这是协方差...但是这不起作用......

设计这样的课程的"正确"方法是什么?

编辑:对不起,我没有100%清楚为什么我无法实现我的需要.

一个.使用通用Base的解决方案不起作用,因为Base的用户不知道T类型.想像:

public class User
{
    private Base<T> base; // this will not compile.
    public User(TypeEnum t)
    {
        if(t == TypeEnum.MyEntity) base = new Child();
...
Run Code Online (Sandbox Code Playgroud)

湾 使用Interface的解决方案不起作用,因为帮助程序在任何地方使用T(它的目的是什么?).想象一下它有方法

public IEnumerable<T> Process(IEnumerable<T> items) { return items; }
Run Code Online (Sandbox Code Playgroud)

如何在不知道任何关于T的界面中提出它

Tim*_* S. 5

我想这就是你所追求的:

public class Base<T> where T : EntityObject
{
    protected Helper<T> helper;
}
public class Child : Base<MyEntity>
{
    public Child()
    {
        helper = new Helper<MyEntity>();
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑(响应您的编辑):您可以添加Base,使用如下:

public class Base
{
    // put anything here that doesn't rely on the type of T
    // if you need things here that would rely on T, use EntityObject and have 
    // your subclasses provide new implementations using the more specific type
}
public class Base<T> : Base where T : EntityObject
{
    protected Helper<T> helper;
}
public class Child : Base<MyEntity>
{
    public Child()
    {
        helper = new Helper<MyEntity>();
    }
}
public class User
{
    private Base myBase;
    public User(TypeEnum t)
    {
        if(t == TypeEnum.MyEntity) myBase = new Child();
        ...
Run Code Online (Sandbox Code Playgroud)