What is the dif开发者_JAVA百科ference between Extension Methods
and Methods
in C#?
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.
精彩评论