,以避免混淆我总结了一些代码:如何在c#中实现泛型多态?
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
IManager<ISpecificEntity> specificManager = new SpecificEntityManager();
IManager<IIdentifier> manager = (IManager<IIdentifier>) specificManager;
manager.DoStuffWith(new SpecificEntity());
}
}
internal interface IIdentifier
{
}
internal interface ISpecificEntity : IIdentifier
{
}
internal class SpecificEntity : ISpecificEntity
{
}
internal interface IManager<TIdentifier> where TIdentifier : IIdentifier
{
void DoStuffWith(TIdentifier entity);
}
internal class SpecificEntityManager : IManager<ISpecificEntity>
{
public void DoStuffWith(ISpecificEntity specificEntity)
{
}
}
}
当我调试的代码我得到了Main()
一个InvalidCastException。
我知道ISpecificEntity
执行IIdentifier
。 但是显然直接从IManager<ISpecificEntity>
转换成IManager<IIdentifier>
不起作用。
我想与协方差的工作可以做的伎俩,但改变IManager<TIdentifier>
到IManager<in TIdentifier>
也没有帮助。
那么,有没有办法将specificManager
转换成IManager<IIdentifier>
?
谢谢,一切顺利。
请阅读:http://stackoverflow.com/questions/245607/how-is-generic-covariance-contra-variance-implemented-in-c-sharp-4-0 – 2012-04-18 14:09:03