开发者

How to group extension methods?

开发者 https://www.devze.com 2023-02-14 21:19 出处:网络
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.Putti

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消