Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

c# - Can There Be Private Extension Methods?

Let's say I have a need for a simple private helper method, and intuitively in the code it would make sense as an extension method. Is there any way to encapsulate that helper to the only class that actually needs to use it?

For example, I try this:

class Program
{
    static void Main(string[] args)
    {
        var value = 0;
        value = value.GetNext(); // Compiler error
    }

    static int GetNext(this int i)
    {
        return i + 1;
    }
}

The compiler doesn't "see" the GetNext() extension method. The error is:

Extension method must be defined in a non-generic static class

Fair enough, so I wrap it in its own class, but still encapsulated within the object where it belongs:

class Program
{
    static void Main(string[] args)
    {
        var value = 0;
        value = value.GetNext(); // Compiler error
    }

    static class Extensions
    {
        static int GetNext(this int i)
        {
            return i + 1;
        }
    }
}

Still no dice. Now the error states:

Extension method must be defined in a top-level static class; Extensions is a nested class.

Is there a compelling reason for this requirement? There are cases where a helper method really should be privately encapsulated, and there are cases where the code is a lot cleaner and more readable/supportable if a helper method is an extension method. For cases where these two intersect, can both be satisfied or do we have to choose one over the other?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Is there a compelling reason for this requirement?

That's the wrong question to ask. The question asked by the language design team when we were designing this feature was:

Is there a compelling reason to allow extension methods to be declared in nested static types?

Since extension methods were designed to make LINQ work, and LINQ does not have scenarios where the extension methods would be private to a type, the answer was "no, there is no such compelling reason".

By eliminating the ability to put extension methods in static nested types, none of the rules for searching for extension methods in static nested types needed to be thought of, argued about, designed, specified, implemented, tested, documented, shipped to customers, or made compatible with every future feature of C#. That was a significant cost savings.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...