What is difference between extension method and static method?

后端 未结 2 1746
暗喜
暗喜 2021-01-05 06:20

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

I have two classes like this :

public static class AClass {
    public stati         


        
2条回答
  •  悲哀的现实
    2021-01-05 06:51

    You cannot override an extension method. Only if the method has a different signature, then it can be overloaded.

    Off course there are some limitations: Extension Methods have to be implemented as static methods and in static classes (inside a non-nested, non-generic static class to be more precise). You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself. Extension methods cannot access private variables in the type they are extending. You can consider Extension Methods as a 'legal' way to add more static methods to existing classes without actually inheriting them. But the funny thing is that unlike regular static methods of the class, you cannot call Extension Methods on a class level (you will get an compile time error if you try this), but instead you must invoke them on a instance of the class (as if they were some regular methods of the instance of that class, which they are not!!!).

    Also, inside the Extension Method you can freely use public properties of the passed object instance on which the method is being invoked, you are by no means limited only to static object data. Only the Extension Method is static method, but the object on which is called is full, regular object instance.

提交回复
热议问题