Specifying the return type of an abstract method from a Base Class according to a Sub Class

前端 未结 4 1183
终归单人心
终归单人心 2020-12-15 07:15

I have the following structure:

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

class SubOne :         


        
相关标签:
4条回答
  • 2020-12-15 07:47

    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(); 
    }
    
    0 讨论(0)
  • 2020-12-15 07:49

    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.
    }
    
    0 讨论(0)
  • 2020-12-15 07:55

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-15 08:00
    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>(); }
    }
    
    0 讨论(0)
提交回复
热议问题