什么时候创建扩展方法是正确的?

发布于 2024-10-15 11:59:55 字数 619 浏览 14 评论 0原文

我有一段如下代码:

public class ActivityHelper
{
    public void SetDate(IList<Activity> anActivityList)
    {
        foreach(Activity current in anActivityList)
        {
            current.Date = DateTime.Now;
        }
    }
    //More methods, properties, fields, etc...
}

这可以很容易地转换为扩展方法。例如:

public static void SetDate(this IList<Activity> aList)
{
    foreach(Activity current in anActivityList)
    {
        current.Date = DateTime.Now;
    }
}

原始函数不使用 ActivityHelper 类中的任何实例特定数据或方法,这使得它看起来像是位于不正确的位置。现在是编写扩展方法的正确时间吗?创建扩展方法的正确场景是什么?

I have a piece of code like the following:

public class ActivityHelper
{
    public void SetDate(IList<Activity> anActivityList)
    {
        foreach(Activity current in anActivityList)
        {
            current.Date = DateTime.Now;
        }
    }
    //More methods, properties, fields, etc...
}

This could easily be converted to an extension method. For example:

public static void SetDate(this IList<Activity> aList)
{
    foreach(Activity current in anActivityList)
    {
        current.Date = DateTime.Now;
    }
}

The original function doesn't use any instance specific data or methods from the ActivityHelper class which makes it seem like it is in the incorrect place. Is this the correct time to write an extension method? What are the correct scenarios in which to create extension methods?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

白首有我共你 2024-10-22 11:59:55

Brad Adams 撰写了有关 的文章扩展方法设计指南

考虑在以下任何场景中使用扩展方法:

  • 提供与接口的每个实现相关的辅助功能(如果所述功能可以根据核心接口编写)。这是因为具体实现不能以其他方式分配给接口。例如,LINQ to Objects 运算符被实现为所有 IEnumerable 类型的扩展方法。因此,任何 IEnumerable<>实现自动启用 LINQ。

  • 当实例方法引入对某种类型的依赖时,但这种依赖会破坏依赖管理规则。例如,从 String 到 System.Uri 的依赖关系可能是不可取的,因此从依赖关系管理的角度来看,返回 System.Uri 的 String.ToUri() 实例方法将是错误的设计。返回 System.Uri 的静态扩展方法 Uri.ToUri(this string str) 会是一个更好的设计。

Brad Adams has written about extension method design guidelines:

CONSIDER using extension methods in any of the following scenarios:

  • To provide helper functionality relevant to every implementation of an interface, if said functionality can be written in terms of the core interface. This is because concrete implementations cannot otherwise be assigned to interfaces. For example, the LINQ to Objects operators are implemented as extension methods for all IEnumerable types. Thus, any IEnumerable<> implementation is automatically LINQ-enabled.

  • When an instance method would introduce a dependency on some type, but such a dependency would break dependency management rules. For example, a dependency from String to System.Uri is probably not desirable, and so String.ToUri() instance method returning System.Uri would be the wrong design from a dependency management perspective. A static extension method Uri.ToUri(this string str) returning System.Uri would be a much better design.

寻找我们的幸福 2024-10-22 11:59:55

我认为只有当有令人信服的理由使该方法成为扩展方法时,扩展方法才是合适的。

如果该类型是您无法控制的类型,并且该方法应该看起来是该类型的组成部分,或者如果有令人信服的理由不将该方法直接放在该类型上(例如创建不需要的依赖项),则可以使用扩展方法可能是合适的。

就个人而言,如果 API 用户的期望已经是在处理 Activity 集合时使用“ActivityHelper”类,那么我可能不会为此创建扩展方法。标准的非扩展方法实际上是一个更简单的 API,因为它很容易理解和发现。从使用的角度来看,扩展方法很棘手 - 您调用的方法“看起来”存在于其他地方,而不是实际存在的地方。虽然这可以简化语法,但会降低可维护性和可发现性。

I think Extension methods are only appropriate if there is a compelling reason to make the method an extension method.

If the type is one you do not control, and the method should appear to be integral to the type, or if there is a compelling reason to not put the method directly on the type (such as creating an unwanted dependency) then an extension method could be appropriate.

Personally, if the expectation of the user of your API will already be to use the "ActivityHelper" class when working with collections of Activities, then I would probably not create an extension method for this. A standard, non-extension method will actually be a simpler API, since it's easily understood and discoverable. Extension methods are tricky from a usage standpoint - you're calling a method that "looks like" it exists somewhere other than where it actually exists. While this can simplify syntax, it reduces maintainability and discoverability.

丑丑阿 2024-10-22 11:59:55

根据我的经验,扩展方法在满足以下条件时效果最佳:

  • 没有副作用(我的团队编写的大多数扩展方法都有副作用,我们最终删除了它们,因为它们造成的问题多于它们提供的帮助)
  • 提供适用于的功能他们正在扩展的类型的每个可能的实例或值。 (再次引用我团队的一个例子,string.NormalizeUrl() 并不合适,因为并非所有字符串都是 URL)

In my experience extension methods work best when they:

  • Don't have side-effects (most of the extension methods my team wrote that have side-effects, we ended up removing because they caused more problems than they helped)
  • Offer functionality that applies to every possible instance or value of the type they're extending. (Again citing an example from my team, string.NormalizeUrl() is not appropriate because not all strings are even URLs anyway)
未蓝澄海的烟 2024-10-22 11:59:55

嗯,我通常创建扩展方法来帮助我编写流畅的代码。它通常取决于您创建的方法。

如果您觉得该方法应该已经在框架中并且太笼统,那么可以为此创建一个扩展方法。

但是您需要首先分析您正在扩展的类将始终处于您的扩展方法可以处理的状态。

有关 Brad 文章的指南

http://blogs.msdn.com/b/brada/archive/2009/01/12/framework-design-guidelines-extension-methods.aspx

Well i usually create extension methods to help me write codes which have a smooth flow. Its generally depends upon the method you are creating.

If you feel that the method should have already been in framework and is too general then its okay to create an extension method for that.

But you need to first analyze that the class you are extending will always will be in state that your extension method can handle.

For Guidelines here to Brad's Article

http://blogs.msdn.com/b/brada/archive/2009/01/12/framework-design-guidelines-extension-methods.aspx

微暖i 2024-10-22 11:59:55

本质上,扩展方法为 Helper 方法提供了更流畅的样式语法。这转化为看似向类型或接口的所有实现添加功能的能力。

但是,我通常会避免使用 void 返回类型来声明扩展方法,因为我觉得这种流畅的样式语法(允许您编写语句)的有用性在相关方法不使用时就被否定了。返回任何东西。

不过,我想让 IntelliSense 拾取你的方法会很方便......:-)

In essence, Extension Methods provide a more fluent style syntax for Helper methods. This translates into the ability to seemingly add functionality to types or all implementations of interfaces.

However, I generally steer away from declaring Extension Methods with a void returntype, as I feel the usefulness of this fluent style syntax, which allows you to compose statements, is negated when the method in question doesn't return anything.

However, I guess it can be handy to have your methods picked up by IntelliSense... :-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文