C # extension Methods Getting Started small case
Definition of extension method:
l must be a static class, static method
< Span style= "" >l first parameter with keyword " this "
code Description: Here's an example of writing a static class, Myextension, an extension method ADD , indicating that all the INT type of numbers will have to call this ADD the ability of the method, the condition is to introduce myextension namespace.
Let's take a look at the usage:
Code Description: What this code does is declare a int type number and assign a value of 7 , and then call ADD method, you will see the following IntelliSense:
you can see that the extension method is marked with a downward-pointing arrow. Then call on it, give it any int, because I used the params keyword, will automatically parse into an int Array, and then use the RLT The variable is received and displayed to see the result:
Example 2:
Write a way to extend the string, you can standardize the English, such as Hello World will be output, Hello World
Using system;using system.collections.generic;using system.linq;using system.text;namespace wpfLab1{public static CLA SS Strextensenclass {public static string Getnormalformat (this string s) {s = Removeextraspa CE (s); string[] Words = S.split ("); string ret = ""; foreach (var word in words) {ret + = STRFSTCHRUPR (word) + ""; } return ret; } public static string Removeextraspace (this string s) {if (s = = NULL | | s.length <= 1) {return s; } bool Lastchrisspace = FALSE; string ret = ""; foreach (Var chr in s) {if (chr = = ") {if (lastchrisspace) {continue; } else {lastchrisspace = true; RET + = CHR; }} else {ret + = CHR; Lastchrisspace = false; }} return ret; } private static string Strfstchrupr (string s) {if (s = = NULL | | S.length < 1) { return s; } String lowerstr = S.tolower (). Remove (0, 1); String upperstr = Char.ToUpper (S[0]). ToString (); Return (Upperstr + lowerstr); } }}
Use:
Using system;using system.collections.generic;using system.linq;using system.text;using System.Windows;using System.windows.controls;using system.windows.data;using system.windows.documents;using System.Windows.Input;using System.windows.media;using system.windows.media.imaging;using system.windows.navigation;using System.windows.shapes;using wpflab1;namespace wpflab1{ ///<summary>//MainWindow.xaml Interactive logic // /</summary> public partial class Mainwindow:window {public MainWindow () { InitializeComponent (); } private void Btnhello_click (object sender, RoutedEventArgs e) { string s = "HEllo world , Hi, World, AA dd DW wwdd a "; Lblhello.content = S.getnormalformat ();}} }
The above is the introduction of C # extension method of the contents of the small case, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!