2017-05-16 10 views
0

の間に違いがあります:コンパイラはジェネリック型を解決できません。

public interface IPathfinding<T> where T : IPathfindingEntity 
{ 
    IEnumerable<T> GetShortestPath(IPathfindingUtils<IGraphNode<T>> utils); 
} 

と:

public interface IPathfinding<T> where T : IPathfindingEntity 
{ 
    IEnumerable<T> GetShortestPath(IPathfindingUtils<IGraphNode<IPathfindingEntity>> utils); 
} 

私はのように直感的に、私は例#でコンパイラエラーを受けていますまだあるはずのように、それはいないようです、私の頭を悩まだが1:

IGraphNode<T> cannot be used as parameter T in the generic type IPathfindingUtils<T>. There is no implicit reference conversion from IGraphNode<T> to IGraphNode<IPathfindingEntity>

は私がIGraphNode<T>またはの定義を変更していませんここで、2つの例をコンパイルしようとしている間は、これらのインターフェースの定義である:

public interface IPathfindingUtils<T> where T : IGraphNode<IPathfindingEntity> 
{ 
    float Heuristic(T from, T to); 
    IEnumerable<T> CreatePath(T from); 
} 

public interface IGraphNode<T> : INode<T>, IComparable<IGraphNode<T>> where T : IComparable<T> 
{ 
    IList<float> Costs { get; } 
} 
+2

共分散と反差別については、https://msdn.microsoft.com/en-us/library/dd799517(v=vs.110).aspx – Chris

+0

を参照してください。前者の例と後者の例は異なります。前者ではTを渡された型として使用していますが、後者のTではテンプレートのみであり、知られていません。私は説明できることを願っています。 –

+0

下記の私の答えを見て、自分の質問に答えてくれたら教えてください。 –

答えて

0

IGraphNodeはIComparableをあるとTが必要です。

だから、あなたはあなたのコードは次のようになりたいでしょう:

public interface IPathfinding<T> where T : IPathfindingEntity, IComparable 
{ 
    IEnumerable<T> GetShortestPath(IPathfindingUtils<IGraphNode<T>> utils); 
} 
+0

IComparableの権利を派生したのはIComparable >ですか? –

0

気にしないで、私はゴムは自分自身をすくめてきたし、問題が何であるかを実現しました。後世のため

:例#1では

T上の制約がIPathfindingEntityあります。 IGraphNode<T>IPathfindingEntityに制限されていないため、IPathfindingUtils<IGraphNode<T>> utilsは有効ではありません。TIPathfindingEntityであり、これは完全充填されていないIGraphNode<T>制約に対するliskov置換を破ります。

解決策は、例2のようにメソッド定義でIPathfindingにIGraphNode制約を指定するだけですか?

関連する問題