简体   繁体   English

抽象类—如何指定返回通用列表

[英]Abstract Class — How to specify return of generic list

I am having some difficulty with this. 我对此有些困难。 I have an abstract class, and I would like to add a public abstract method for its inheritors to implement. 我有一个抽象类,我想为其继承者添加一个公共抽象方法。 The challenge is that the method should return a generic list of classes that implement a totally different abstract class (NotifyingDatabaseObject). 面临的挑战是该方法应返回实现完全不同的抽象类(NotifyingDatabaseObject)的类的通用列表。

I'd like to do something like the following, but it won't compile: 我想执行以下操作,但无法编译:

public abstract IList<T> GetList(int? id) where T : NotifyingDatabaseObject;

And, of course, if I replace "T" with "NotifyingDatabaseObject", it will require the inheriting classes to return that abstract class instead of concrete ones. 而且,当然,如果我将“ T”替换为“ NotifyingDatabaseObject”,它将要求继承的类返回该抽象类,而不是具体的抽象类。

Any direction on how I can accomplish this? 关于如何实现此目标的任何方向?

Thanks! 谢谢!

If the returning type has no relation to the abstract or the concrete class, you can use a type parameter on the method, like: 如果返回的类型与抽象类或具体类无关,则可以在方法上使用类型参数,例如:

public abstract IList<T> GetList<T>(int? id) where T : NotifyingDatabaseObject;

The concrete class would be something like: 具体的类如下所示:

class MyConcreteClass : MyAbstractClass
{
    public override IList<NotifyingDatabaseObjectChildClass> GetList<NotifyingDatabaseObjectChild>(int? id)
    {
        return new List<NotifyingDatabaseObjectChildClass>();
    }
}

I assume you want each subclass of your base class to return a particular subtype of NotifyingDatabaseObject . 我假设您希望基类的每个子类都返回NotifyingDatabaseObject特定子类型。 In this case you should add a type parameter to the base class and have each subtype specify which subtype of NotifyingDatabaseObject they return: 在这种情况下,您应该在基类中添加一个类型参数,并让每个子类型指定它们返回的NotifyingDatabaseObject子类型:

public abstract class MyAbstractClass<T>
    where T : NotifyingDatabaseObject
{
    public abstract IList<T> GetList(int? id) ;
}

public class MyConcreteClass : MyAbstractClass<NotifyingDatabaseObjectChildClass>
{
    public override IList<NotifyingDatabaseObjectChildClass> GetList(int? id)
    {
        return new List<NotifyingDatabaseObjectChildClass>();
    }
}

Note the existing answer does not do this - it requires each subtype to support returning a list of any subtype of NotifyingDatabaseObject , not just one in particular. 请注意,现有答案不会这样做-它要求每个子类型都支持返回NotifyingDatabaseObject任何子类型的列表,而不仅仅是返回一个子列表。 In this case the only possible implementation is to return an empty list (or null, or throw an exception, or loop infinitely), since the implementing classes have no general way of constructing a value of type T . 在这种情况下,唯一可能的实现是返回一个空列表(或为null,或者引发异常,或者无限循环),因为实现类没有构造T类型值的通用方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM