c# - IList<IClient> 方法<T>() 其中 T : Iclient can not add client object to list

标签 c# .net generics generic-method

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/

相关文章:

java - 获取 java.util.List 的泛型类型

java - 在循环 Java 7 中转换泛型类型

c# - bool 不更新

c# - .NET XML : What is the . NET 相当于 XmlDocument.TransformNode?

c# - LINQ XML 将不同的层次结构读入 1 个对象

c# - 内存不足异常,即使有 30 GB 内存可用

c# - 正则表达式从js代码中提取地址

c# - 如何确定cefsharp版本

c# - 用户 'myUser' @'DESKTOP-1FSAS' 的访问被拒绝(使用密码 : NO)

ios - 使用泛型扩展 UIView