public IList GetClientsByListofID(IList ids) 其中 T : IClient { IList 客户 = new List(); clients.Add(新客户端(3));
我在这里遇到编译器错误:
无法从“Bailey.Objects.Client”转换为“T”
客户端对象实现了 IClient 接口(interface)。我的目标是尝试放松我的类(class)之间的耦合(学习 DI 东西 atm)。我在想我可以说它可以使用任何类型的客户端对象,并且会被返回。
我在这里完全偏离基地了吗?
谢谢
乔恩·霍金斯
最佳答案
您不能以这种方式使用通用约束。编译器如何保证类型参数是 Client
仅仅因为它实现了 IClient
接口(interface)?许多类型不能实现该接口(interface)吗?
在这种情况下(在需要使用类型而不是接口(interface)的情况下)最好用类型本身来约束类型参数,如下所示:
public IList<T> GetClientsByListofID<T>(IList<int> ids) where T : Client
{
IList<T> clients = new List<T>();
clients.Add(new Client(3));
// ...
}
一旦这样做,我想知道您是否需要一个通用方法:
public IList<Client> GetClientsByListofID(IList<int> ids)
{
IList<Client> clients = new List<Client>();
clients.Add(new Client(3));
// ...
}
关于c# - IList<IClient> 方法<T>() 其中 T : Iclient can not add client object to list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/747576/