extension methods enable you to "add" methods to an existing type without creating a new derived type, recompiling, or otherwise modifying the original type. an extension method is a special static method, but it can be called just like an instance method on an extended type. for client code written in C # and Visual Basic, there is no significant difference between calling extension methods and calling methods that are actually defined in the type.
to use the standard query operators, first use using system.linq directives place them in scope. Then, any type that implements the ienumerable<t> appears to have an instance method of GroupBy, by-and-Average, and so on.
The following example shows how to call the standard query operator by way of an array of integers. The expression inside the parentheses is a lambda expression. Many standard query operators use lambda expressions as parameters, but this is not a requirement for extension methods. For more information, see Lambda Expressions (C # Programming Guide).
C#
class ExtensionMethods2
{ static void Main()
{
int[] ints = { 10, 45, 15, 39, 21, 26 }; var result = ints.OrderBy(g => g); foreach (var i in result)
{
System.Console.Write(i + " ");
}
}
}//Output: 10 15 21 26 39 45
extension methods are defined as static methods, but they are called through the instance method syntax. Their first argument specifies which type the method acts on, and the parameter is prefixed with the This modifier. extension methods are only in scope when you explicitly import namespaces into the source code using a using directive.
The following example shows an extension method defined for the System.String class. Note that it is defined inside a non-nested, non-generic static class:
C#
namespace ExtensionMethods
{ public static class MyExtensions
{ public static int WordCount(this String str)
{ return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
You can use this using directive to place the WordCount extension method in scope:
Using Extensionmethods;
Also, you can invoke the extension method from the application using the following syntax:
string s = "Hello Extension Methods";
int i = s.WordCount();
in code, you can call the extension method using the instance method syntax. However, the compiler-generated intermediate language (IL) translates the code into a call to a static method. Therefore, the encapsulation principle is not really violated. in fact, extension methods cannot access private variables in the types they extend.
For more information, see How to: Implement and invoke a custom extension method (C # Programming Guide).
Typically, you are more often calling extension methods instead of implementing your own extension methods. Because extension methods are invoked using instance method syntax, you do not need any special knowledge to use them from the client code. to enable extension methods for a particular type, simply add a using directive for the namespace in which the methods are defined. For example, to use the standard query operators, add this using directive to your code:
Using System.Linq;
(you may also have to add a reference to System.Core.dll. You will notice that the standard query operator is now displayed in IntelliSense as an additional method for use by most ienumerable<t> types.
description |
Although the standard query operators are not displayed in the String in IntelliSense, but they are still available. |
Binding extension method at compile time
when compiling, the extension method will always have a lower precedence than the instance method defined in the type itself. in other words, if a type has a name process (int i) method, and you have an extension method with the same signature, the compiler is always bound to that instance method. when the compiler encounters a method call, it first looks for a matching method in the instance method of that type. If no matching method is found, the compiler searches for any extension methods defined for the type, and binds to the first extension method it finds.
example
static class The Extensions contains the implementation for any imyinterface The extension method for the type definition. A , b and c implements this interface.
The MethodB extension method is never called because its name and signature exactly match the methods that these classes have implemented.
If the compiler cannot find an instance method with a matching signature, it binds to the matching extension method (if such a method exists).
C#
// Define an interface named IMyInterface.namespace DefineIMyInterface
{ using System; public interface IMyInterface
{ // Any class that implements IMyInterface must define a method
// that matches the following signature.
void MethodB();
}
}// Define extension methods for IMyInterface.namespace Extensions
{ using System; using DefineIMyInterface; // The following extension methods can be accessed by instances of any
// class that implements IMyInterface.
public static class Extension
{ public static void MethodA(this IMyInterface myInterface, int i)
{
Console.WriteLine
("Extension.MethodA(this IMyInterface myInterface, int i)");
} public static void MethodA(this IMyInterface myInterface, string s)
{
Console.WriteLine
("Extension.MethodA(this IMyInterface myInterface, string s)");
} // This method is never called in ExtensionMethodsDemo1, because each
// of the three classes A, B, and C implements a method named MethodB
// that has a matching signature.
public static void MethodB(this IMyInterface myInterface)
{
Console.WriteLine
("Extension.MethodB(this IMyInterface myInterface)");
}
}
}// Define three classes that implement IMyInterface, and then use them to test// the extension methods.namespace ExtensionMethodsDemo1
{ using System; using Extensions; using DefineIMyInterface; class A : IMyInterface
{ public void MethodB() { Console.WriteLine("A.MethodB()"); }
} class B : IMyInterface
{ public void MethodB() { Console.WriteLine("B.MethodB()"); }
public void MethodA(int i) { Console.WriteLine("B.MethodA(int i)"); }
} class C : IMyInterface
{ public void MethodB() { Console.WriteLine("C.MethodB()"); }
public void MethodA(object obj)
{
Console.WriteLine("C.MethodA(object obj)");
}
} class ExtMethodDemo
{ static void Main(string[] args)
{ // Declare an instance of class A, class B, and class C.
A a = new A();
B b = new B();
C c = new C(); // For a, b, and c, call the following methods:
// -- MethodA with an int argument
// -- MethodA with a string argument
// -- MethodB with no argument.
// A contains no MethodA, so each call to MethodA resolves to
// the extension method that has a matching signature.
a.MethodA(1); // Extension.MethodA(object, int)
a.MethodA("hello"); // Extension.MethodA(object, string)
// A has a method that matches the signature of the following call
// to MethodB.
a.MethodB(); // A.MethodB()
// B has methods that match the signatures of the following
// method calls.
b.MethodA(1); // B.MethodA(int)
b.MethodB(); // B.MethodB()
// B has no matching method for the following call, but
// class Extension does.
b.MethodA("hello"); // Extension.MethodA(object, string)
// C contains an instance method that matches each of the following
// method calls.
c.MethodA(1); // C.MethodA(object)
c.MethodA("hello"); // C.MethodA(object)
c.MethodB(); // C.MethodB()
}
}
}/* Output:
Extension.MethodA(this IMyInterface myInterface, int i)
Extension.MethodA(this IMyInterface myInterface, string s)
A.MethodB()
B.MethodA(int i)
B.MethodB()
Extension.MethodA(this IMyInterface myInterface, string s)
C.MethodA(object obj)
C.MethodA(object obj)
C.MethodB()
*/
general criteria
in general, it is recommended that you implement extension methods only when you have to, and implement them with caution. whenever possible, client code that must extend an existing type should achieve this by creating a new type derived from an existing type. For more information, see Inheritance (C # Programming Guide).
When you use an extension method to extend a type that you cannot change the source code for, you need to bear the risk that the changes in that type implementation will invalidate the extension method.
If you do implement an extension method for a given type, keep in mind the following points:
-
If the extension method has the same signature as the method defined in the type, the extension method is never called.
-
For example, if you are in a name extensions has multiple static classes in the namespace that contain extension methods, these extension methods will all be using Extensions; Instruction is placed in scope.
For an implemented class library, you should not use an extension method to avoid incrementing the version number of the assembly. If you want to add important functionality to a library where you have source code, you should follow the standard. NET Framework guidelines that apply to assembly version control. For more information, see Assembly version control.
The above is the C # parameter with this what meaning (extension method) content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!