私はまだ、ジェネリックで共分散と反分散を使うときに、制約を理解するのが難しいです。Contravariance/Covariance、なぜこれをキャストできませんか?
私はこれがあれば、なぜ私は、不思議:
public interface IFasterListCov<out T>
{}
public interface IFasterListCon<in T>
{}
public class FasterList<T> : IList<T>, IFasterListCov<T>, IFasterListCon<T>
を第三のキャストが失敗した:あなたがあなたの最後のキャストが取得するためには、QueryNodes<MyNode>
を呼んでいるシナリオでは
public void QueryNodes<T>() where T:INode
{
//somehow I can convert IFasterListCon<INode> to IFasterListCon<T>
IFasterListCon<INode> nodes = (IFasterListCon<INode>)_nodesDB[type];
//I guess this works because _nodesDB[type] is indeed a FasterList<T> object
//note: I am wrong, I can cast whatever INode implementation, not just T, which made me very confused :P
IFasterListCon<T> nodesT = (IFasterListCon<T>)nodes;
//I can't cast IFasterListCon<T> back to FasterList<T>
FasterList<T> nodeI = nodesT as FasterList<T>; //null
}
Dictionary<Type, IFasterListCov<INode>> _nodesDB;
to be clear _nodesDB[type] is a FasterList<T> declared through IFasterListCov<INode>
nodesT' 'の_actual_タイプは何ですか?基礎となる型が互換性がある場合にのみ機能する_downcast_を実行しています。 –
あなたはTとは何ですか? TはINodeを実装しなければなりません(constrainはwhere節にあります)... ah ok _nodesDBには全てのFasterListが含まれています –
sebas
'FasterList'は 'FasterList 'ではありません。 –
Lee