我将让代码进行讨论:

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>());
        }
    }
}

如果ThingServiceInstanceIThingServiceInstanceMyThingIThing,为什么不能将ThingServiceInstance<MyThing>添加到IThingServiceInstance<IThing>的集合中?

我该怎么做才能编译此代码?

最佳答案

ThingServiceInstance<MyThing>而非IThingServiceInstance<IMyThing>的子类型,因为IThingServiceInstance<T>的类型参数<T>是不变的。

如果要使ThingServiceInstance<MyThing>IThingServiceInstance<IMyThing>的子类型,则T必须是协变的。
在C#中,您可以这样声明IThingServiceInstance<T>来做到这一点:

public interface IThingServiceInstance<out T>

编辑
但是,这意味着ThingServiceInstance<T>只能返回T的实例,而不能将它们用作方法参数(因此使用“out”表示法)。

编辑2

这就是为什么您的代码未编译的要点。如前所述,由于您的ThingServiceInstance<T>公开了IThingRepository<T>属性,因此也必须像这样协变:
public interface IThingRepository<out T> where T : class, IThing { }

如下所示,您的属性必须是只读的(请记住,您只能返回TU<T>的实例)。

关于c# - 无法将通用接口(interface)的具体实例添加到通用集合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19979721/

10-12 03:28