C#使用在具体的类声明中引用自身的泛型

时间:2019-09-07 22:42:48

标签: c# generics interface

来自Java,我认为我应该能够执行以下操作:

using System.Collections.Generic;

interface ICoord<T> where T : ICoord<T>
{
    ICollection<T> GetNeighbors();
}


class SquareCoord : ICoord<SquareCoord>
{
    public ICollection<SquareCoord> GetNeighbors() {
        throw new System.NotImplementedException();
    }
}


interface IGrid<T> where T : ICoord<T>
{
    List<T> GetGrid();
}


// This works no problem (everything is concretely defined)
class SquareGrid : IGrid<SquareCoord>
{
    public List<SquareCoord> GetGrid() {
        throw new System.NotImplementedException();
    }
}


class Grid : IGrid<ICoord>
{
    public List<ICoord> GetGrid() 
    {
        //do stuff
    }
}

最后一个类Grid应该能够操作并返回任何ICoord(具体实现)的列表。

我有一个使用Java的小型工作示例。如果我能在C#中获得等效的代码(如果可能的话),那将给我足够的机会。

public class Example {
    private interface Index<T extends Index> {
        List<T> GetNeighbors();
    }

    private static class SquareIndex implements Index<SquareIndex> {
        public List<SquareIndex> GetNeighbors(){
            return new ArrayList<>();
        }
    }

    private interface Grid<T extends Index> {
        List<T> GetGrid();
    }

    // Java does not require a type parameter to implement "Grid"
    private static class MyGrid implements Grid {
        // Java allows me to satisfy the requirements for implementing "Grid"
        // without having a concrete type defined in the method declaration.
        public List<? extends Index> GetGrid() {
            final List<SquareIndex> result = new ArrayList<>();
            result.add(new SquareIndex());
            return result;
        }
    }

    public static void main(String[] args) {
        MyGrid g = new MyGrid();
        g.GetGrid();
    }
}

1 个答案:

答案 0 :(得分:1)

我出色的女友刚刚发现:

class MyGrid<T> : IGrid<T> where T : ICoord<T>
{
    public List<T> GetGrid() {
        throw new System.NotImplementedException();
    }
}