简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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