我正在编写用于处理无向图的类,并且遇到以下编译时错误:
最佳重载方法匹配
'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
不同,并且我收到警告,指出应重命名它们。我可以做到,但这不会影响错误。我认为该片段的目的很明确,那么我如何使它做我想做的事情以及我的想法在哪里出错呢? 最佳答案
您确定存在三个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) { }
}
}