开发者

Can someone explain what Extension Methods are in C# and how the work [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

What are Extension Meth开发者_如何学运维ods?

Can someone explain what Extension Methods are in C# and how the work in layman's terms and if possible some examples please


Extension methods are syntactic sugar for static method calls.

The following are equivalent:

Extension:

public static int GetLength(this string s)
{
    return s.Length;
}

s.GetLength();

Static:

public static int GetLength(string s)
{
  return s.Length;
}

SomeClass.GetLength(s);


In summary, Extension Method is syntax sugar, allowing to create a method in fact not belonging to type. Indeed, that's just a static method threated by compiler as a member "native".

Assuming you have a type:

class Test
{
    void Foo();
}

Let's declare an extension method:

static class Extensions
{
    public void Bar(this Foo) { }
}

Now you can call it:

new Test().Foo(); // "native" method
new Test().Bar(); // extension method

In fact that's just this:

public static void Bar(Test t) { }


I think you can already find enough references on this topic on the web, like this MSDN article.

In a nutshell, extension methods allow you to extend a class without deriving it. They are some particular static methods, belonging to a static class. They always start with a parameter of the type they extend, prefixed with the keyword this. Let's say you want a method to return the extension of a file from a string (hope the logic is right, didn't check it actually):

public static class FileExtension
{
    public static string Extension(this string filename)
    {
        int index = filename.LastIndexOf('.');
        if(index > 0)
            return filename.Substring(index, filename.length - index);

        return filename;
    }
}

And then you can say:

string filename = "c:\temp\sample.txt";
string ext = filename.Extension();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜