我正在编写一个用于处理无向图的类,并遇到了以下编译时错误:
最佳重载方法匹配 'Dictionary.EdgeCollection> .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) { }
}
}
请注意,嵌套类中的TVertex
和TEdge
与外部类中的TVertex
和TEdge
不同,我收到警告,说明我应该重命名它们。我可以这样做,但这不会影响错误。我认为片段的目的是明确的,那么如何让它做我想做的事情以及我的想法出错了?
答案 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) { }
}
}