C # extension method using

  • Extension method allows you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
  • Extension method is a special kind of static method, but can be called as an instance method on the same type of extensions
  • Extension method is defined as static methods, but they are invoked by the instance method syntax. Their first argument specifies the type which acts on the method, and the parameter modifier of this prefix. After only when you are using directive explicitly namespace introduced into the source code, the method was extended in the range of.
    • Using directive must be explicitly namespace introduced into the source code, otherwise the visual studio may be positioned to define the extension of the method, but still wrong compiled
  • priority
    • Extension methods may be used to extend a class or interface, but can not rewrite the extension method. Extension method with the same name and signature of the interface or class method is never called.
    • Compile-time, extension methods always lower than the priority of the type defined in the example method itself. In other words, if a type having a called Process (int i) of the method,
    • And you have an extension method has the same signature, the compiler always bound to the instance method. When the compiler encounters a method call, it first looks for the matching method in this type of instance methods.
    • If no matching method is found, the compiler will search for any type of extension methods defined and binds to the first extension method that it finds.
namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' }, 
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }   
}


using ExtensionMethods;

string s = "Hello Extension Methods";
int i = s.WordCount();

Guess you like

Origin www.cnblogs.com/wyp1988/p/11389299.html