从通用超类定义中获取正确的子类方法

时间:2013-10-23 13:49:17

标签: c# generics inheritance

我如何实现多个子类中超类中定义的泛型方法? 我需要正确的子类方法由调用子类实例的类型决定:

var someClassObj = new SubClass();
var = someClassObj.BuildList(v1, v2);

public abstract class SomeBase
{
    public List<T> BuildList<T>(int v1, int v2)
    {
        var results = new List<T>();

        for (int i = v1; i < v2; i++)
        {
            results.Add(AddItem<T>());
        }
        return results;
    }

    protected abstract T AddItem<T>();
}

public class SubClass : SomeBase
{


    protected override BusinessThing AddItem<T>()
    {
        var entity = new BusinessThing();
        entity.Name1 = "1";
        entity.Name2 = "2";
        entity.Name3 = "3";
        return entity;
    }
}

public class BusinessThing
{
    public string Name1 { get; set; }
    public string Name2 { get; set; }
    public string Name3 { get; set; }
}

上面没有构建:覆盖方法时无法更改返回类型&#39; T SomeBase.AddItem()&#39;

2 个答案:

答案 0 :(得分:3)

您可以使您的基类通用而不是其方法:

public abstract class SomeBase<T>
{
    public List<T> BuildList(int v1, int v2)
    {
        var results = new List<T>();

        for (int i = v1; i < v2; i++)
        {
            results.Add(AddItem());
        }
        return results;
    }

    protected abstract T AddItem();
}

public class SubClass : SomeBase<BusinessThing>
{
    protected override BusinessThing AddItem()
    {
        var entity = new BusinessThing();
        entity.Name1 = "1";
        entity.Name2 = "2";
        entity.Name3 = "3";
        return entity;
    }
}

答案 1 :(得分:1)

如果您不想像Daniel建议的那样拥有泛型类,您还可以告诉编译器T使用where子句来限制泛型类型:

public abstract class SomeBase
{
    public List<T> BuildList<T>(int v1, int v2) where T: BusinessThing
    {
        var results = new List<T>();

        for (int i = v1; i < v2; i++)
        {
            results.Add(AddItem<T>());
        }
        return results;
    }

    protected abstract T AddItem<T>() where T:BusinessThing;
}

public class SubClass : SomeBase
{
    protected override T AddItem<T>()
    {
        var entity = new BusinessThing();
        entity.Name1 = "1";
        entity.Name2 = "2";
        entity.Name3 = "3";
        return (T)entity;
    }
}

然后按如下方式使用:

var someClassObj = new SubClass();
var list = someClassObj.BuildList<BusinessThing>(5, 7);

这也允许您使用派生的ConcreteBusinessThing类,该类派生自BusinessThing,它也可以使用:

public class SubClass : SomeBase
{
    protected override T AddItem<T>()
    {
        var entity = new ConcreteBusinessThing();
        entity.Name1 = "1";
        entity.Name2 = "2";
        entity.Name3 = "3";
        return (T)(object)entity; // ugly cast but is always ok
    }
}

并用:

调用它
var someClassObj = new SubClass();
var list = someClassObj.BuildList<ConcreteBusinessThing>(5, 7);