Extension methods
Add a method dynamically to an existing type without creating a new derived type, recompiling or modifying the source of the original type
An extension method is a special static method that is called in the same way as a normal instance method
? extension Method Use Example
public static void PrintString(this String val)
{
Console.WriteLine(val);
var a Span class= "pun" >= "AAA"
printstring
/span>console readkey
But with our code above, we have "extended" a printstring method to the string type.
(1) Prerequisites
<1> extension methods must be defined in a non-nested, non-generic static class
The <2> extension method must be a static method
<3> extension methods must have at least one parameter
<4> The first parameter must be appended with the This keyword as a prefix
<5> The first parameter cannot have other modifiers (such as ref or out)
<6> The first parameter cannot be a pointer type
(2) Precautions
<1> as with several of the preceding features, the extension method only increases the compiler's work and does not affect performance (adding attributes to a type in an inherited way can affect performance)
<2> If there is a method in the original class that is the same as your extension method (at least it is the same), then your extension method award will not be called and the compiler will not prompt you
<3> extension methods are too powerful to affect architecture, patterns, readability, etc...
An example of your own writing
public static class father
{
public static int Speak(this int i) {
Console.WriteLine("this is a test{0}",i);
return i+20;
}
}
int ii = 10;
Console.WriteLine(ii.Speak());
From for notes (Wiz)
extension methods in C #