我已經發布this question with a bad sample。如何在c#中實現泛型多態 - 第2部分?
此代碼應該更好。
爲了避免混淆,我總結了一些代碼:
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; }
}
}
當我調試的代碼我在第12行
得到一個InvalidCastException在Main()
我知道ISpecificEntity
實現IIdentifier
。 但是顯然直接從IManager<ISpecificEntity>
轉換成IManager<IIdentifier>
不起作用。
我認爲使用協方差可以做到這一點,但將IManager<TIdentifier>
更改爲IManager<in TIdentifier>
或IManager<out TIdentifier>
也不起作用。
那麼,有沒有辦法將specificManager
轉換成IManager<IIdentifier>
?
謝謝,一切順利。
應該告訴你哪些主要的線()是有問題的。你能告訴我們嗎? – 2012-04-18 15:50:12
可能的重複[如何在c#中實現泛型多態?](http://stackoverflow.com/questions/10211072/how-to-implement-generic-polymorphism-in-c) – 2012-04-18 15:54:40
不要重新發布,編輯和改進你的問題。 – 2012-04-18 15:56:15