Jon*_*Jon 2 .net c# generics generic-method
public IList GetClientsByListofID(IList ids)其中T:IClient {IList clients = new List(); clients.Add(new Client(3)); }
我在这里得到一个编译器错误:
无法从'Bailey.Objects.Client'转换为'T'
客户端对象实现IClient接口.我的目标是尝试放松我的课程之间的耦合(学习DI的东西).我想我可以说它可以使用任何类型的客户端对象,并将返回.
我完全不在这里吗?
谢谢
乔恩霍金斯
您不能以这种方式使用通用约束.编译器如何保证type参数Client只是因为它实现了IClient接口?有多少类型不能实现该接口?
在这种情况下(在你需要使用类型而不是接口的情况下)最好用类型本身约束type参数,如下所示:
public IList<T> GetClientsByListofID<T>(IList<int> ids) where T : Client
{
IList<T> clients = new List<T>();
clients.Add(new Client(3));
// ...
}
Run Code Online (Sandbox Code Playgroud)
一旦这样做,我想知道你是否需要一个通用的方法:
public IList<Client> GetClientsByListofID(IList<int> ids)
{
IList<Client> clients = new List<Client>();
clients.Add(new Client(3));
// ...
}
Run Code Online (Sandbox Code Playgroud)