2

我正在编写一个用于处理无向图的类,并遇到以下编译时错误:

'Dictionary.EdgeCollection>.Add(TVertex, UndirectedGraph.EdgeCollection)' 的最佳重载方法匹配有一些无效参数

论点 2:不能转换 fromUndirectedGraph<TVertex,TEdge>.AdjacentEdgeCollection<TVertex,TEdge>UndirectedGraph<TVertex,TEdge>.AdjacentEdgeCollection<TVertex,TEdge>

我可以将问题简化为以下示例:

public class UndirectedGraph<TVertex, TEdge>
{
    Dictionary<TVertex, EdgeCollection<TVertex, TEdge>> edges;

    class VertexCollection<TVertex, TEdge>
    {
        UndirectedGraph<TVertex, TEdge> graph;

        public VertexCollection(UndirectedGraph<TVertex, TEdge> graph)
        { this.graph = graph; }

        public void Add(TVertex value)
        {
            // Argument 2: cannot convert
            // from 'UndirectedGraph<TVertex,TEdge>.AdjacentEdgeCollection<TVertex,TEdge>'
            //   to 'UndirectedGraph<TVertex,TEdge>.AdjacentEdgeCollection<TVertex,TEdge>'
            this.graph.edges.Add(value, new EdgeCollection<TVertex, TEdge>(this.graph));
        }
    }

    class EdgeCollection<TVertex, TEdge>
    {
        public EdgeCollection(UndirectedGraph<TVertex, TEdge> graph) { }
    }
}

请注意,TVertex嵌套TEdge类中的TVertexandTEdge与外部类中的 and 不同,并且我收到警告说我应该重命名它们。我可以这样做,但这不会影响错误。我认为片段的目的很明确,那么我如何让它做我想做的事情,我的想法哪里出错了?

4

1 回答 1

4

你确定有三个TVertex类型参数和三个TEdge类型参数?在我看来,这三个都是相同的,您需要的是以下内容:

public class UndirectedGraph<TVertex, TEdge>
{
    Dictionary<TVertex, EdgeCollection> edges;

    class VertexCollection
    {
        UndirectedGraph<TVertex, TEdge> graph;

        public VertexCollection(UndirectedGraph<TVertex, TEdge> graph)
        { this.graph = graph; }

        public void Add(TVertex value)
        {
            this.graph.edges.Add(value, new EdgeCollection(this.graph));
        }
    }

    class EdgeCollection
    {
        public EdgeCollection(UndirectedGraph<TVertex, TEdge> graph) { }
    }
}
于 2012-10-12T21:54:37.130 回答