代码之家  ›  专栏  ›  技术社区  ›  Jon

ilist<iclient>method<t>(),其中t:iclient无法将客户端对象添加到列表中

  •  2
  • Jon  · 技术社区  · 15 年前

    public ilist getclientsbylistofid(ilist id),其中t:iclient { ilist clients=new list(); clients.add(新客户端(3)); }

    我在这里收到一个编译器错误:

    无法从“bailey.objects.client”转换为“t”

    客户端对象实现IClient接口。我的目标是尝试放松我的课程之间的耦合(学习di-stuff-atm)。我在想,我可以说它可以使用任何类型的客户机对象,这将被返回。

    我在这里完全不在基地吗?

    谢谢

    乔恩霍金斯

    5 回复  |  直到 15 年前
        1
  •  5
  •   Andrew Hare    15 年前

    不能以这种方式使用泛型约束。编译器如何保证类型参数是 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));
        // ...
    }
    
        2
  •  1
  •   ybo    15 年前

    Client 是一个 IClient . T 是一个 ICLITENT .

    你在哪里说的? T 是一个 顾客 ?无处可去!

    我想你需要一个 IClientFactory IClientRepository 这将为您创建/检索IClient实例。然后您将能够使用这个工厂/存储库的不同实现。

        3
  •  1
  •   tvanfosson    15 年前

    试试这个:

    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 );
    
        4
  •  1
  •   Joseph    15 年前

    你的问题不在约束范围之内

    where T : IClient
    

    而是在使用你的列表。

    你不能这样说:

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

    您可以这样说:(这假定您的约束包括“new”)。

    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类型是client类型,这就是为什么它会给你编译器错误。这与你的约束没有任何关系。

        5
  •  0
  •   bruno conde    15 年前

    因为在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;
        }
    

    …但我想知道你是否需要仿制药。