gpt4 book ai didi

c# - 允许推断模板

转载 作者:太空狗 更新时间:2023-10-29 20:39:40 24 4
gpt4 key购买 nike

假设我正在使用 external package for storing graphs . BidirectionalGraph 采用两个模板:顶点和边类型:

var graph = new BidirectionalGraph<Vertex, Edge<Vertex>>();

不幸的是,这个图形包不允许您在一条直线上将边辐射到一个顶点。相反,您必须提供 IEnumerable ,它将用结果填充。这可能会破坏良好的编码节奏,因为“遍历所有顶点 x 的后继顶点”之类的任务需要太多代码。

我想使用 .NET 的扩展来为图形类添加一个单行解决方案:

public static class GraphExtensions
{
public static IEnumerable<TEdge> IncomingEdges<TGraphSubtype, TVertex, TEdge>(this TGraphSubtype graph, TVertex n)
where TGraphSubtype : BidirectionalGraph<TVertex, TEdge>
where TEdge : IEdge<TVertex>
{
IEnumerable<TEdge> inputEdgesForVertex;
graph.TryGetInEdges(n, out inputEdgesForVertex);
return inputEdgesForVertex;
}
}

但是当我调用 graph.IncomingEdges(vertex) ,出于某种原因 C#(.NET 4.5 版)无法推断模板参数,所以我不得不说:

graph.IncomingEdges<GraphThatInheritsFromBidirectionalGraph<VertexType,EdgeType>,VertexType,EdgeType>(vertex) .并不是很大的改进。

第一,为什么不能估计模板类型?我有一种感觉,它与继承有关,但不明白。我习惯使用 C++,出于某种原因,我觉得 gcc 可以推断模板类型。

其次,如果这种情况无法避免,那么从 BidirectionalGraph 继承的图形类是否是正确的设计选择?必须重写构造函数似乎很浪费,但我相信您会同意使用显式模板类型调用方法是不雅的。

编辑:

奇怪的是,等效规范(下面)确实允许模板类型的自动推断。因此,即使它解决了我最初的问题(将此功能添加到图表中),我仍然很想了解。

public static class GraphExtensions
{
public static IEnumerable<TEdge> IncomingEdges<TVertex, TEdge>(this BidirectionalGraph<TVertex,TEdge> graph, TVertex n)
where TEdge : IEdge<TVertex>
{
IEnumerable<TEdge> inputEdgesForVertex;
graph.TryGetInEdges(n, out inputEdgesForVertex);
return inputEdgesForVertex;
}
}

最佳答案

您的扩展方法的第一个版本能够推断出 TGraphTypeTVertex但不是 TEgde ,因为它需要推断 TEdge来自类型约束:

where TGraphSubtype : BidirectionalGraph<TVertex, TEdge>

C# 编译器不会这样做(它不会从类型约束中推断泛型类型参数)。老实说,我不知道这背后是否有技术原因,或者只是没有实现。

另一方面,您的更新版本包括 BidirectionalGraph<TVertex, TEdge>作为参数,例如,当您在类上调用扩展方法时:

class AGraph: BidirectionalGraph<AVertex, AnEdge> { ... }
...
var aGraph = new AGraph();
aGraph.IncomingEdges(vertex);

编译器能够检查类型 AGraph并看到有一个独特的类型 BidirectionalGraph<AVertex, AnEdge>在它的继承层次结构中,所以它能够推断出 TVertexTEdge .

注意如果参数类型是IGraph<TVertex, TEdge> (而不是 BidirectionalGraph<TVertex, TEdge> )和 AGraph实现了该通用接口(interface)的多个构造类型,例如:

class AGraph: IGraph<AVertex, AnEdge>, 
IGraph<AnotherVertex, AnotherEdge> { ... }

然后类型推断将再次失败,因为它无法判断,例如,TVertexAVertexAnotherVertex .

关于c# - 允许推断模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18272837/

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