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
202 views
in Technique[技术] by (71.8m points)

c# - What is difference between extension method and static method?

What is the difference between an extension method and a static method ?

I have two classes like this :

public static class AClass {
    public static int AMethod(string ....)
    {
    }
}

and

public static class BClass {
    public static int BMethod(this string ....)
    {
    }
}

I can use these like

AClass.AMethod('...');

or

'...'.BMethod();

Which is proposed ?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

An extension method is still a static method. You can use it exactly as you'd use a normal static method.

The only difference is that an extension method allows you to use the method in a way that looks like it's part of the type, so you can write:

int result = stringValue.BMethod();

Instead of:

int result = BClass.BMethod(stringValue);

This works purely as a compile "trick" - the compiler sees the first form, and if the BClass is usable (it has a proper using and is in a referenced assembly), then it will turn it into the second method's IL for you. It's purely a convenience.

Which is proposed ?

This really depends. If you control the type, I'd recommend putting the methods on the type itself. This is typically more maintainable.

If you don't control the type, or you're trying to "extend" a common type (such as IEnumerable<T>), then extension methods may be a reasonable approach.

However, if the type is a very common type, I'd typically avoid extension methods, as they become "noise" in intellisense, which in turn can cause extra confusion. For example, I would personally not recommend adding extension methods on System.Object or System.String, etc.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...