gpt4 book ai didi

c# - 通用类型与扩展方法

转载 作者:行者123 更新时间:2023-12-01 19:41:03 25 4
gpt4 key购买 nike

我需要对两种技术进行比较:使用泛型类型和扩展类型。我的意思不是一般比较,我的意思是在这种特定情况下,当我需要向名为 ClassA

的类添加一些功能时
  1. 使用泛型类型

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

  2. 使用扩展方法

    通过添加其扩展方法来使用ClassA

     public static class Helper
    {

    public static void MethodOne(this ClassA obj, )

    {
    //
    }

    }

我需要知道:

  • 与其他技术相比,每种技术有哪些优势?
  • 为什么存储库模式中总是使用第一种技术?例如在这个 implementation为什么我们不向全局类Entity添加扩展方法?

最佳答案

这是两个完全不同的事情。

您使用泛型来提供泛型功能。对于存储库,这通常与包含所有实体实现的属性的“基本实体”类或接口(interface)一起使用,例如 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);
}

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

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

另请参阅When do you use extension methods, ext. methods vs. inheritance? , What is cool about generics, why use them? .

关于c# - 通用类型与扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30120424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com