【问题标题】:Generic list in an interface接口中的通用列表
【发布时间】:2009-03-24 06:00:50
【问题描述】:

我正在尝试实现一个包含对象列表的接口类。如何使列表通用,以便实现类定义列表的类型:

public interface IEntity
{
    Guid EntityID { get; set; }
    Guid ParentEntityID{ get; set; }
    Guid RoleId { get; set; }

    void SetFromEntity();
    void Save();
    bool Validate();
    IQueryable<T> GetAll(); // That is what I would like to do
    List<Guid> Search(string searchQuery);
}
public class Dealer : IEntity
{
   public IQueryable<Dealer> GetAll() { }
}

【问题讨论】:

    标签: c# linq generics generic-list


    【解决方案1】:

    你可以这样做:

    public interface IEntity<T>
    {
        IQueryable<T> GetAll();
    }
    
    public class Dealer : IEntity<Dealer>
    {
       public IQueryable<Dealer> GetAll() { }
    }
    

    【讨论】:

      【解决方案2】:

      您只需要将 IEntity 本身设为通用。然后,在 GetAll() 的定义中使用类型参数。

      以下是更改代码的方法:

      public interface IEntity<TListItemType>
      {
           // stuff snipped
      
           IQueryable<TListItemType> GetAll();
      }
      
      public class Dealer : IEntity<Dealer>
      {
         public IQueryable<Dealer> GetAll() { // some impl here }
      }
      

      【讨论】:

        【解决方案3】:

        将Save()、Validate() 等逻辑添加到您的域对象(我猜这就是Dealer)并不是世界上最好的主意,因为它违反了SRP。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-05
          相关资源
          最近更新 更多