通用嵌套类型:无法从X <t>转换为X <t> </t> </t>

时间:2012-10-12 21:32:21

标签: c# generics

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

  

最佳重载方法匹配   'Dictionary.EdgeCollection&gt; .Add(TVertex,UndirectedGraph.EdgeCollection)'   有一些无效的论点

     

参数2:无法转换   来自UndirectedGraph<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) { }
    }
}

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

1 个答案:

答案 0 :(得分: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) { }
    }
}