通用类型与扩展方法

Lam*_*fif 2 .net c# oop generics extension-methods

我需要在两种技术之间进行比较:使用泛型类型和扩展类型.我不是指一般的比较,我的意思是在这种特殊情况下我需要为一个名为类的类添加一些功能ClassA

  1. 使用泛型类型

    使用泛型类型(Where T: ClassA)并实现泛型方法

  2. 使用扩展方法

    使用ClassA添加其扩展方法

     public static class Helper
    {
    
     public static void MethodOne(this ClassA obj, )
    
     {
     //
      }
    
     }
    
    Run Code Online (Sandbox Code Playgroud)

我需要知道 :

  • 与其他技术相比,每种技术的优势是什么?
  • 为什么总是使用第一种技术Repository Pattern?例如,在此实现中,为什么我们不向全局类添加扩展方法Entity

Cod*_*ter 5

这是两件完全不同的事情.

您使用泛型来提供通用功能.对于存储库,这通常与"基本实体"类或包含所有实体实现的属性的接口一起使用,例如ID:

public interface IEntity
{
    int ID { get; set; }
}

public class Client : IEntity
{
    public int ID { get; set; }
    public string Name { get; set; }        
}

public class Repository<T> 
    where T : IEntity
{
    private readonly IQueryable<T> _collection;
    public Repository(IQueryable<T> collection)
    {
        _collection = collection;
    }

    public T FindByID(int id)
    {
        return _collection.First(e => e.ID == id);
    }
}
Run Code Online (Sandbox Code Playgroud)

您也可以使用扩展方法执行此操作:

public static T FindByID(this IQueryable<T> collection, int id)
    where T : IEntity
{
    return collection.First(e => e.ID == id);
}
Run Code Online (Sandbox Code Playgroud)

如果没有泛型,您必须为每种类型实现存储库或扩展方法.

在这种情况下,为什么不使用扩展方法:通常只在不能扩展基类型时才使用扩展方法.使用存储库类,您可以将操作分组到一个逻辑类中.

另请参见何时使用扩展方法,分机.方法与继承?,什么是酷的仿制药,为什么使用它们?.