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

标签 c# .net extension-methods design-guidelines

我有一段代码如下:

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 类中的任何实例特定数据或方法,这使得它看起来像是在错误的位置。现在是编写扩展方法的正确时机吗?创建扩展方法的正确场景是什么?

最佳答案

Brad Adams 写过关于 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.

关于c# - 什么时候创建扩展方法是正确的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4857683/

相关文章:

c# - 关于使用枚举作为参数和 if/else 条件的问题

c# - 如何 "Free"一个线程

.net - Azure AppFabric 与服务器 AppFabric - 今天

c# - 使用 C# 查找和替换字符串中的文本

c# - 异步 CTP - 环境 CancellationToken 和 IProgress

.net - MQMessage 探索(使用 WebSphere MQ .NET API)

.net - 将 Haskell 与 .Net 集成?

c# - 我的扩展方法没有注册

C#检查属性的扩展方法

c# - 将方法作为扩展方法调用比直接调用需要更多的引用