Tôi sẽ cho các mã làm như nói chuyện:Không thể thêm một trường hợp cụ thể của một giao diện chung để một bộ sưu tập chung
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>());
}
}
}
Nếu ThingServiceInstance
là một IThingServiceInstance
và MyThing
là một IThing
, tại sao có thể không Tôi thêm một ThingServiceInstance<MyThing
> vào bộ sưu tập của IThingServiceInstance<IThing>
?
Tôi có thể làm gì để biên dịch mã này?
[Hiệp phương sai và Contravariance trong Generics] (http://msdn.microsoft.com/en-us/library/dd799517 (v = vs.110).aspx) – Jehof
Tìm kiếm với từ khóa "Hiệp phương sai và đối nghịch" –