gpt4 book ai didi

c# - 无法将通用接口(interface)的具体实例添加到通用集合

转载 作者:太空狗 更新时间:2023-10-29 23:23:09 25 4
gpt4 key购买 nike

我会让代码来说话:

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是一个 IThingServiceInstanceMyThing是一个 IThing ,为什么我不能添加 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com