我有代码结构:如何投放类型,它的通用基类型
SpecificType.cs
public class SpecificType : TypeBase<SpecificT, SpecificV>
where T : ITBase
where V : IVBase
{ ... }
SpecificT.cs
public class SpecificT : ITBase { ... }
SpecificV.cs
public class SpecificV : IVBase { ... }
TypeBase.cs
public class TypeBase<T, V> : IBase<T, V>
where T : ITBase
where V : IVBase
{ ... }
IBase.cs
public interface IBase<T, V>
where T : ITBase
where V : IVBase
{ ... }
所有我想要做的就是投我SpecificType
到它的最抽象的类型 - IBase<T,V>
:
SpecificType specTypeObject = new SpecificType();
IBase<ITBase, IVBase> typeObject = (IBase<ITBase, IVBase>)specTypeObject;
所有我收到的是InvalidCastException
。这我甚至想实现吗?
为什么你需要做显式强制转换,因为你到了基类?你如何在实现中使用类型属性?只在输入位置或输出位置? – neo
[MSDN:泛型中的协变和反变量](https://msdn.microsoft.com/en-us/library/dd799517%28v=vs.110%29.aspx) – Dmitry
您使用哪个.NET版本? – neo