问题
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.
回答1:
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
回答2:
Why not:
ISpecificEntity bankAccountManager = new SpecificEntity();
IManager<IIdentifier> manager = (IManager<IIdentifier>)bankAccountManager;
manager.DoStuffWith(new SpecificEntity());
?
来源:https://stackoverflow.com/questions/10211072/how-to-implement-generic-polymorphism-in-c