开发者

Please explain extension methods to me

I just looked at this posting: What is the best or most interesting use of Extension Methods 开发者_如何转开发you’ve seen?

I've never heard of extension methods. Do they apply to every language?

What is the point of them? In that particular posting I did not understand the example.


No, they do not apply to every language. They are a language-specific feature, offered by C# and Visual Basic (other languages may have adopted them since, I don't know).

The point of them is to provide a convenient syntax for calling utility methods on a class or interface. In C# 2, a utility method would be called through a static class, passing the argument in the normal way:

IEnumerable<string> someStrings;
int count = EnumerableHelpers.Count(someStrings);

With extension methods, this can be written more conveniently using something that looks like normal member method syntax:

int count = someStrings.Count();

even though Count() is not a member of the IEnumerable<string> interface. So extension methods let you appear to add members to classes or interfaces that you don't control.


They are available to C# and VB. They allow you to simulate the addition of methods to classes that are not under your control.

You could, for instance, you could add a WordCount method to string.

So instead of

MyStringUtils.WordCount( "some string" )

You could just write "some string".WordCount().

public static class MyExtensions
{
    public static int WordCount(this String str)
    {
        return MyStringUtils.WordCount( str );
    }
} 

This is strictly "syntactic sugar" and aids in readability. You're essentially creating a static method that will be shown in the IntelliSense for the target type.


do they apply to every language?

No, but some languages have the same feature, though not necessarily under the same name. Those I know about are Objective-C and Groovy, where the feature is called "Categories".

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜