简体   繁体   中英

Difference between Extension methods and Methods in C#

C#中的Extension MethodsMethods什么区别?

I think what you are really looking for is the difference between Static and Instance Methods

At the end of the day Extension methods are some nice compiler magic and syntactic sugar that allow you to invoke a Static method as though it were a method defined on that particular class instance. However, it is NOT an instance method, as the instance of that particular class must be passed into the function.

ExtensionMethods : Let you define set of methods to a class without subclassing another benefit over inheritance.

Methods : They are used for implementation of operation defind for the the class.

See example of Extension Methods

One really nice feature of extension methods is that they can be called on null objects, see this:

myclass x = null;
x.extension_method(); // this will work
x.method(); // this won't

It is a pity, that for example most methods of string are not extension methods, after all

x.ToLower();

should return null if x is null. I mean, it would be useful.

When I need such null-transparency I prefer writing extension methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM