Return 与子类调用基方法的类型相同

Return the same type as subclass calling a base method

一个非常简单的基础class:

class Figure {
    public List<?> getList() {
        var list = new List<same as child>();
        //do some code
        //filling list
        return list;
    }
}

此继承class:

class Rectangle : Figure
{
    
}
class Cube : Figure
{
    
}

我知道我可以像这样使用泛型:

class Figure {
    public List<T> getList<T>() {
        var list = new List<T>();
        //do some code
        //filling list
        return list;
    }
}

Rectangle rec = new Rectangle();
List<Rectangle> lRec = rec.getList<Rectangle>();

Cube cube = new Cube();
List<Cube> lCube = cube.getList<Cube>();

但是我想知道有没有其他选择

像这样:

Rectangle rec = new Rectangle();
List<Rectangle> lRec = rec.getList();

Cube cube = new Cube();
List<Cube> lCube = cube.getList();

如果将类型参数限制为实现 class 你得到了你要找的东西:

class Figure<T> where T : Figure<T>
{
    public List<T> getList()
    {
        var list = new List<T> ();
        //do some code
        //filling list
        return list;
    }
}

class Rectangle : Figure<Rectangle>
{

}
class Cube : Figure<Cube>
{

}

根据场景将getList标记为虚拟或抽象可能会派上用场