简体   繁体   English

如何对扩展方法进行分组?

[英]How to group extension methods?

I have a static class with bunch of extension methods for various types. 我有一个静态类,其中包含各种类型的扩展方法。 Is there any utility or the way to split it into several classes - separate class for the each target type. 是否有任何实用程序或将其分为几个类的方法-每个目标类型的单独类。

Putting your various extension methods into different classes is a good idea from a "clean code" perspective, but the main "grouping" of extension methods happens by placing them into different namespaces. 从“干净的代码”的角度来看,将各种扩展方法放入不同的类中是一个好主意,但是扩展方法的主要“分组”是通过将它们放入不同的命名空间来实现的。 The reason is that extension methods are made available by "using" the appropriate namespace. 原因是可以通过“使用”适当的名称空间来使用扩展方法。

Putting different groups of extension methods into different namespaces is a good idea since you could have colliding extension methods. 将不同的扩展方法组放入不同的名称空间是一个好主意,因为您可能会遇到冲突的扩展方法。 If that happens, and each logical group of extension methods is in a fine-grained namespace, you should be able to resolve the conflict by simply removing one of the using statements, thereby leaving the using statement that contains the extension method you actually want. 如果出现这种情况,和扩展方法,每个逻辑组是在一个细粒度的命名空间,你应该能够通过简单地移除的一个解决冲突using的语句,从而留下using语句包含你真正想要的扩展方法。

Here's a link to some best practices: 以下是一些最佳做法的链接:

http://blogs.msdn.com/b/vbteam/archive/2007/03/10/extension-methods-best-practices-extension-methods-part-6.aspx http://blogs.msdn.com/b/vbteam/archive/2007/03/10/extension-methods-best-practices-extension-methods-part-6.aspx

I have another way of grouping: 我有另一种分组方式:

public class StringComplexManager
{
    public StringComplexManager(String value)
    {
        Value = value;
    }

    public String Value { get; set; }
}

public static class StringComplexExtensions
{
    public static StringComplexManager ComplexOperations(this String value)
    {
        return new StringComplexManager(value);
    }

    public static int GetDoubleLength(this StringComplexManager stringComplexManager)
    {
         return stringComplexManager.Value.Length * 2;
    }
}

Usage is: 用法是:

string a = "Hello"
a.ComplexOperations().GetDoubleLength()

ComplexOperation() groups the extension methods and narrows the intellisense scope so that if you originally had hundreds of string extension methods you now only see one in intellisense. ComplexOperation()对扩展方法进行分组,并缩小了智能感知的范围,因此,如果您最初有数百种字符串扩展方法,则现在只能在智能感知中看到一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM