Covariance in C# generic class

喜你入骨 提交于 2019-12-01 22:36:22

If Foo : Bar, that doesn't mean that Some<Foo> : Some<Bar>. There are two ways of doing what you want. The first is to make the base-type generic such that:

Base<T> where T : EntityObject {
    protected Helper<T> helper;
}
Child : Base<MyEntity> {...}

The second is to use a non-generic interface at the base-type, i.e. have

Base {
    protected IHelper helper;
}
Child : Base {...}

where in the latter case, Helper<T> : IHelper, for some non-generic IHelper to-be-defined.

As a side-note, you might find it easier to pass the value down in the constructor rather than using a protected field.

I think this is what you're after:

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

Edit (in response to your edit): You can add a Base, use like so:

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();
        ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!