【发布时间】:2016-05-19 20:56:48
【问题描述】:
面对现实吧,当需要在泛型中使用协变和逆变时,我仍然难以理解约束。
我想知道,为什么我有这个:
public interface IFasterListCov<out T>
{}
public interface IFasterListCon<in T>
{}
public class FasterList<T> : IList<T>, IFasterListCov<T>, IFasterListCon<T>
第三次施法失败:
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的 实际 类型是什么?你正在做一个 downcast 只有在底层类型兼容的情况下才有效。 -
你的意思是什么是T? T 必须实现 INode(约束在 where 子句中)...啊 好的 _nodesDB 包含所有 FasterList
-
除非
T是INode,否则FasterList<INode>不是FasterList<T>。 -
所以 T 实现 INode 还不够?我的意思是在内存中仍然是两种情况下的参考,对吗?数据结构应该是兼容的。
标签: c# casting covariance contravariance