通用类型与扩展方法
Generic type vs Extension method
我需要对两种技术进行比较:使用泛型类型和扩展类型。我的意思不是一般比较,我的意思是在这种特定情况下,当我需要向名为 ClassA
的 class 添加一些功能时
使用通用类型
使用泛型类型 (Where T: ClassA
) 并实现泛型方法
使用扩展方法
通过添加其扩展方法来使用 ClassA
public static class Helper
{
public static void MethodOne(this ClassA obj, )
{
//
}
}
我需要知道:
- 与其他技术相比,每种技术的优势是什么?
- 为什么
Repository Pattern
总是用第一种技术?例如,在这个 implementation 为什么我们不向全局 class Entity
添加扩展方法?
这是完全不同的两件事。
您使用泛型来提供泛型 功能。对于存储库,这通常与 "base entity" class 或包含所有实体实现的属性的接口一起使用,例如 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);
}
}
您也可以使用扩展方法来做到这一点:
public static T FindByID(this IQueryable<T> collection, int id)
where T : IEntity
{
return collection.First(e => e.ID == id);
}
如果没有泛型,您必须为每个类型实现存储库或扩展方法。
在这种情况下为什么不使用扩展方法:通常只在无法扩展基类型时才使用扩展方法。使用存储库 class,您可以将操作分组在一个逻辑 class.
中
另见 When do you use extension methods, ext. methods vs. inheritance?, What is cool about generics, why use them?。
我需要对两种技术进行比较:使用泛型类型和扩展类型。我的意思不是一般比较,我的意思是在这种特定情况下,当我需要向名为 ClassA
使用通用类型
使用泛型类型 (
Where T: ClassA
) 并实现泛型方法使用扩展方法
通过添加其扩展方法来使用
ClassA
public static class Helper { public static void MethodOne(this ClassA obj, ) { // } }
我需要知道:
- 与其他技术相比,每种技术的优势是什么?
- 为什么
Repository Pattern
总是用第一种技术?例如,在这个 implementation 为什么我们不向全局 classEntity
添加扩展方法?
这是完全不同的两件事。
您使用泛型来提供泛型 功能。对于存储库,这通常与 "base entity" class 或包含所有实体实现的属性的接口一起使用,例如 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);
}
}
您也可以使用扩展方法来做到这一点:
public static T FindByID(this IQueryable<T> collection, int id)
where T : IEntity
{
return collection.First(e => e.ID == id);
}
如果没有泛型,您必须为每个类型实现存储库或扩展方法。
在这种情况下为什么不使用扩展方法:通常只在无法扩展基类型时才使用扩展方法。使用存储库 class,您可以将操作分组在一个逻辑 class.
中另见 When do you use extension methods, ext. methods vs. inheritance?, What is cool about generics, why use them?。