简体   繁体   中英

Generic list in an interface

I am trying to implement an interface class, that contains a list of objects. How can I make the list generic, so that the implementing class defines the type of list:

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() { }
}

You can do something like this:

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

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

You just need to make IEntity generic itself. Then, use the type parameter in the definition of GetAll().

Here's how you'd change your code:

public interface IEntity<TListItemType>
{
     // stuff snipped

     IQueryable<TListItemType> GetAll();
}

public class Dealer : IEntity<Dealer>
{
   public IQueryable<Dealer> GetAll() { // some impl here }
}

Adding Save() , Validate() , etc. logic to your domain object (which is what a Dealer is, I guess) is not the best idea in the world as it violates SRP .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM