简体   繁体   中英

How to implement generic polymorphism in 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

Why not:

ISpecificEntity bankAccountManager = new SpecificEntity();
IManager<IIdentifier> manager = (IManager<IIdentifier>)bankAccountManager;
manager.DoStuffWith(new SpecificEntity());

?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM