我已经用一个坏样本发布了这个问题。
这段代码应该更好。
为了避免混淆,我总结了一些代码:
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
IManager<ISpecificEntity> specificManager = new SpecificEntityManager();
IManager<IAntoherSpecificEntity> anotherSpecificManager = new AnotherSpecificEntityManager();
Dictionary<string, IManager<IIdentifier>> managers = new Dictionary<string, IManager<IIdentifier>>();
managers.Add("SpecificManager", (IManager<IIdentifier>)specificManager);
managers.Add("AnotherSpecificManager", (IManager<IIdentifier>)anotherSpecificManager);
foreach (var manager in managers.Values)
{
IIdentifier entity = manager.Container.GetEntity();
}
}
}
internal interface IIdentifier
{
int Id { get; set; }
}
internal interface ISpecificEntity : IIdentifier
{
string SpecificValue { get; set; }
}
internal class SpecificEntity : ISpecificEntity
{
public int Id { get; set; }
public string SpecificValue { get; set; }
}
internal interface IAntoherSpecificEntity : IIdentifier
{
string AnotherSpecificValue { get; set; }
}
internal class AntoherSpecificEntity : IAntoherSpecificEntity
{
public int Id { get; set; }
public string AnotherSpecificValue { get; set; }
}
internal interface IContainer<out TIdentifier> where TIdentifier : IIdentifier
{
TIdentifier GetEntity();
}
internal interface ISpecificContainer : IContainer<ISpecificEntity>
{
}
internal class SpecificContainer : ISpecificContainer
{
public ISpecificEntity GetEntity()
{
return new SpecificEntity { SpecificValue = "SpecificValue" };
}
}
internal interface IAnotherSpecificContainer : IContainer<IAntoherSpecificEntity>
{
}
internal class AnotherSpecificContainer : IAnotherSpecificContainer
{
public IAntoherSpecificEntity GetEntity()
{
return new AntoherSpecificEntity { AnotherSpecificValue = "AnotherSpecificValue" };
}
}
internal interface IManager<TIdentifier> where TIdentifier : IIdentifier
{
IContainer<TIdentifier> Container { get; set; }
}
internal class SpecificEntityManager : IManager<ISpecificEntity>
{
public IContainer<ISpecificEntity> Container { get; set; }
}
internal class AnotherSpecificEntityManager : IManager<IAntoherSpecificEntity>
{
public IContainer<IAntoherSpecificEntity> Container { get; set; }
}
}
当我调试代码时,我Main()
在第 12 行得到一个 InvalidCastException。
我知道ISpecificEntity
实现IIdentifier
. 但显然从 an 直接IManager<ISpecificEntity>
转换为 anIManager<IIdentifier>
是行不通的。
我认为使用协方差可以解决问题,但更改IManager<TIdentifier>
为IManager<in TIdentifier>
或IManager<out TIdentifier>
也不起作用。
那么,有没有办法强制specificManager
转换成IManager<IIdentifier>
?
谢谢,一切顺利。