我有一小段代碼正在通過串列檢查重疊:
private List<INode> _nodes = new List<INode>();
private List<ISegment> _segments = new List<ISegment>();
public IReadOnlyList<INode> Nodes => _nodes;
public IReadOnlyList<ISegment> Segments => _segments;
private bool Overlaps<T>(ref Vector3 point, in IReadOnlyList<T> collection, out T obj) where T : INode, ISegment
{
obj = default;
for (int i = 0; i < collection.Count; i )
{
if (collection[i].Overlaps(ref point))
return true;
}
return false;
}
public bool Overlaps(ref Vector3 point, out INode node){
return Overlaps(ref point, _nodes, out node);
}
public bool Overlaps(ref Vector3 point, out ISegment segment){
return Overlaps(ref point, _segments, out segment);
}
通用方法只能接受兩種型別,INode 或 ISegment,這是該where子句的用途,但我收到此錯誤:
The type 'Graphs.INode' cannot be used as type parameter 'T' in the generic type or
method 'Graph.Overlaps<T>(ref Vector3, in IReadOnlyList<T>, out T)'. There is no
implicit reference conversion from 'Graphs.INode' to 'Graphs.ISegment'.
不確定我理解為什么它認為我正在轉換,我在where這里使用的關鍵字是否錯誤?不知道如何使它作業。
介面定義:
public interface INode{
bool Overlaps(ref Vector3 point);
}
public interface ISegment{
bool Overlaps(ref Vector3 point);
}
uj5u.com熱心網友回復:
where關鍵字表示您的 Generic 型別必須實作INode AND ISegment。
INode 和 ISegments 似乎具有相同的合同,您可以基于此構建介面繼承。
public interface INode{
bool Overlaps(ref Vector3 point);
}
public interface ISegment : INode { }
//OR
public interface ISegment {
bool Overlaps(ref Vector3 point);
}
public interface INode : ISegment { }
更新
更好的方法是使用公共共享介面
public interface IOverlaps {
bool Overlaps(ref Vector3 point);
}
public interface INode : IOverlaps { }
public interface ISegment : IOverlaps { }
... where T : IOverlaps { ... }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/460190.html
