Specifying the return type of an abstract method f

2020-02-09 03:44发布

I have the following structure:

abstract class Base {
        public abstract List<...> Get(); //What should be the generic type?
}

class SubOne : Base {
    public override List<SubOne> Get() {

    }
}

class SubTwo : Base {
    public override List<SubTwo> Get() {

    }
}

I want to create an abstract method that returns whatever class the concrete sub class is. So, as you can see from the example, the method in SubOne should return List<SubOne> whereas the method in SubTwo should return List<SubTwo>.

What type do I specify in the signature declared in the Base class ?


[UPDATE]

Thank you for the posted answers.

The solution is to make the abstract class generic, like such:

abstract class Base<T> {
        public abstract List<T> Get();
}

class SubOne : Base<SubOne> {
    public override List<SubOne> Get() {

    }
}

class SubTwo : Base<SubTwo> {
    public override List<SubTwo> Get() {

    }
} 

4条回答
够拽才男人
2楼-- · 2020-02-09 04:04

I don't think you can get it to be the specific subclass. You can do this though:

abstract class Base<SubClass> {
        public abstract List<SubClass> Get(); 
}
class SubOne : Base<SubOne> {
    public override List<SubOne> Get() {
        throw new NotImplementedException();
    }
}
class SubTwo : Base<SubTwo> {
    public override List<SubTwo> Get() {
        throw new NotImplementedException();
    }
}
查看更多
虎瘦雄心在
3楼-- · 2020-02-09 04:06

Your abstract class should be generic.

abstract class Base<T> {
        public abstract List<T> Get(); 
}

class SubOne : Base<SubOne> {
    public override List<SubOne> Get() {

    }
}

class SubTwo : Base<SubTwo> {
    public override List<SubTwo> Get() {
    }
}

If you need to refer to the abstract class without the generic type argument, use an interface:

interface IBase {
        //common functions
}

abstract class Base<T> : IBase {
        public abstract List<T> Get(); 
}
查看更多
Melony?
4楼-- · 2020-02-09 04:14
public abstract class Base<T> 
{       
    public abstract List<T> Get(); 
}

class SubOne : Base<SubOne> 
{
    public override List<SubOne> Get() { return new List<SubOne>(); }
}

class SubTwo : Base<SubTwo> 
{
    public override List<SubTwo> Get() { return new List<SubTwo>(); }
}
查看更多
该账号已被封号
5楼-- · 2020-02-09 04:18

Try this:

public abstract class Base<T> {
  public abstract List<T> Foo();
}

public class Derived : Base<Derived> {   // Any derived class will now return a List of
  public List<Derived> Foo() { ... }     //   itself.
}
查看更多
登录 后发表回答