2

公共 IList GetClientsByListofID(IList ids) 其中 T : IClient { IList clients = new List(); 客户。添加(新客户(3));}

我在这里遇到编译器错误:

无法从“Bailey.Objects.Client”转换为“T”

客户端对象实现 IClient 接口。我的目标是尝试放松我的类之间的耦合(学习 DI 的东西 atm)。我在想我可以说它可以使用任何类型的客户端对象并且会被返回。

我完全不在这儿吗?

谢谢

乔恩·霍金斯

4

5 回答 5

5

您不能以这种方式使用通用约束。编译器如何保证类型参数Client只是因为它实现了IClient接口?许多类型不能实现该接口吗?

在这种情况下(即在您需要使用类型而不是接口的情况下)最好使用类型本身来约束类型参数,如下所示:

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));
    // ...
}
于 2009-04-14T13:32:02.517 回答
1

Client是一个IClientT是一个IClient

你在哪里指定这T是一个Client?无处!

我认为您需要一个IClientFactoryorIClientRepository来为您创建/检索 IClient 实例。然后,您将能够使用此工厂/存储库的不同实现。

于 2009-04-14T13:36:27.937 回答
1

试试这个:

public interface IClient
{
    string Name { get; }
}

public class Client : IClient
{
    public string Name { get; set; }
}

     ...

public IList<T> GetClientsByListofID<T>( IList<int> ids )
         where T : class, IClient
{
    var clients = new List<T>();
    var client = new Client { Name = "bob" } as T;

    clients.Add( client );

    return clients;
}

用法:

     var clients = this.GetClientsByListOfID<Client>( null );
于 2009-04-14T13:55:54.130 回答
1

您的问题不在约束范围内

where T : IClient

而是在使用您的列表时。

你不能这样说:

IList<T> clients = new List<T>();
clients.Add( new Client(3));

你可以这样说:(这假设你的约束包括“新”)

IList<T> clients = new List<T>();
clients.Add( new T());

在这种情况下,您的约束将需要是:

    where T : new(), IClient

或者你可以这样做,但它根本不会使用泛型:

IList<T> clients = new List<Client>();
clients.Add( new Client(3));

你不能做你想做的事情的原因是因为编译器不能保证类型 T 将是客户端类型,这就是它给你编译器错误的原因。它实际上与您的约束没有任何关系。

于 2009-04-14T14:10:21.333 回答
0

您正在做的事情不起作用,因为在 C# 3.0 中,泛型不支持协变。

你可以这样做:

    interface IClient
    {
        int Id { get; set; }
    }

    class Client : IClient
    {
        public int Id { get; set; }
        public Client() { }
    }

    // ...

    public IList<T> GetClientsByListofID<T>(IList<int> ids) where T : IClient, new()
    {
        IList<T> clients = new List<T>();
        clients.Add(new T() { Id = 3 });
        // ...
        return clients;
    }

...但我想知道你是否需要泛型。

于 2009-04-14T14:00:33.917 回答