我讓代碼來說話:不能通用接口的具體實例添加到泛型集合
using System.Collections.Generic;
namespace test
{
public interface IThing { } // can't change this - it's a 3rd party thing
public interface IThingRepository<T> where T : class, IThing { } // can't change this - it's a 3rd party thing
public interface IThingServiceInstance<T>
where T : class, IThing
{
IThingRepository<T> Repository { get; set; }
}
public class ThingServiceInstance<T> : IThingServiceInstance<T> where T : class, IThing
{
public IThingRepository<T> Repository { get; set; }
}
public class MyThing : IThing
{
}
class Test
{
public void DoStuff()
{
IList<IThingServiceInstance<IThing>> thingServiceInstances = new List<IThingServiceInstance<IThing>>();
// the following line does not compile. Errors are:
// 1: The best overloaded method match for 'System.Collections.Generic.ICollection<test.IThingServiceInstance<test.IThing>>.Add(test.IThingServiceInstance<test.IThing>)' has some invalid arguments C:\TFS\FACE\ResearchArea\ArgonServiceBusSpike\Argon_Service_Bus_Spike_v2\Argon.ServiceLayer\test.cs 31 13 Argon.ServiceGateway
// 2: Argument 1: cannot convert from 'test.ThingServiceInstance<test.MyThing>' to 'test.IThingServiceInstance<test.IThing>' C:\TFS\FACE\ResearchArea\ArgonServiceBusSpike\Argon_Service_Bus_Spike_v2\Argon.ServiceLayer\test.cs 31 39 Argon.ServiceGateway
// Why? ThingServiceInstance is an IThingServiceInstance and MyThing is an IThing
thingServiceInstances.Add(new ThingServiceInstance<MyThing>());
}
}
}
如果ThingServiceInstance
是一個IThingServiceInstance
和MyThing
是IThing
,爲什麼不能我添加一個ThingServiceInstance<MyThing
>到IThingServiceInstance<IThing>
的集合?
我能做些什麼來使代碼編譯?
[泛型中的協變和逆變](http://msdn.microsoft.com/en-us/library/dd799517(v = vs.110))。aspx) – Jehof
搜索關鍵字「協方差與反變量」 –