如何实现在C#泛型多态? [英] How to implement generic polymorphism in c#?

查看:784
本文介绍了如何实现在C#泛型多态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

,以避免混淆我总结了一些代码:



<预类=郎-CS prettyprint-覆盖> 命名空间的ConsoleApplication1
{
类项目
{
静态无效的主要()
{
iManager中< ISpecificEntity> specificManager =新SpecificEntityManager();
iManager中< IIdentifier>经理=(iManager中< IIdentifier>)specificManager;
manager.DoStuffWith(新SpecificEntity());
}
}

内部接口IIdentifier
{
}

内部接口ISpecificEntity:IIdentifier
{
}

内部类SpecificEntity:ISpecificEntity
{
}

内部接口iManager中< TIdentifier>其中,TIdentifier:IIdentifier
{
无效仅在Python标准(TIdentifier实体);
}

内部类SpecificEntityManager:iManager中< ISpecificEntity>
{
公共无效仅在Python标准(ISpecificEntity specificEntity)
{
}
}
}

当我调试的代码,我得到的Main()。



我知道 ISpecificEntity 工具 IIdentifier
但是显然从 iManager中℃的直投; ISpecificEntity> iManager中< IIdentifier> 不起作用



我以为协方差的工作可以做的伎俩,但改变 iManager中< TIdentifier> iManager中<在TIdentifier方式> 并没有帮助



那么,有没有办法做投 specificManager iManager中< IIdentifier>



感谢和所有的最好的。


解决方案

通过 iManager中< IIdentifier> 你可以做这样的事情:

  IIdentifier实体=新NotSpecificEntity(); 
manager.DoStuffWith(实体);

这将导致异常,在你的 SpecificEntityManager ,因为它接受类型的参数只有 ISpecificEntity



更新:
你可以阅读更多关于协方差和逆变在C#在埃里克利珀的博客


to avoid confusion I summarised some code:

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)
        {
        }
    }
}

When I debug the code I get an InvalidCastException in Main().

I know that ISpecificEntity implements IIdentifier. But obviously a direct cast from an IManager<ISpecificEntity> into an IManager<IIdentifier> does not work.

I thought working with covariance could do the trick but changing IManager<TIdentifier> into IManager<in TIdentifier> does not help either.

So, is there a way do cast specificManager into an IManager<IIdentifier>?

Thanks and all the best.

解决方案

With IManager<IIdentifier> you can do such thing:

IIdentifier entity = new NotSpecificEntity();
manager.DoStuffWith(entity);

That will lead to exception, in your SpecificEntityManager, because it accepts only parameters of type ISpecificEntity

UPDATE: You can read more about covariance and contravariance in C# at Eric Lippert's blog

这篇关于如何实现在C#泛型多态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆