gpt4 book ai didi

c# - 通用嵌套类型 : cannot convert from X to X

转载 作者:行者123 更新时间:2023-11-30 21:03:26 26 4
gpt4 key购买 nike

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

The best overloaded method match for 'Dictionary.EdgeCollection>.Add(TVertex, UndirectedGraph.EdgeCollection)' has some invalid arguments

Argument 2: cannot convert from UndirectedGraph<TVertex,TEdge>.AdjacentEdgeCollection<TVertex,TEdge> to 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在外部类中,我收到警告说我应该重命名它们。我可以这样做,但这不会影响错误。我觉得这个fragment的目的很明确,那我怎么让它做我想做的事,我的思路错在哪里呢?

最佳答案

你确定有3个TVertex类型参数和3个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) { }
}
}

关于c# - 通用嵌套类型 : cannot convert from X<T> to X<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12867396/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com