C #3.0 provides this mechanism to add attributes or methods to classes, such as adding a method to strings.
Namespace myextensionmethods {
Public static class myextensions {
Public static int mygetlength (this system. String target)
{
Return target. length;
}
}
}
Grouping method:
Public static class stringextension
{
Public static chinesestring aschinesestring (this string s) {return New chinesestring (s );}
Public static convertablestring asconvertablestring (this string s) {return New convertablestring (s );}
Public static regexablestring asregexablestring (this string s) {return New regexablestring (s );}
}
Public class chinesestring
{
Private string S;
Public chinesestring (string s) {This. S = s ;}
// Convert the fullwidth
Public String tosbc (string input) {Throw new notimplementedexception ();}
// Turn to the halfwidth
Public String todbc (string input) {Throw new notimplementedexception ();}
// Obtain the first letter of the Chinese alphabet
Public String getchinesespell (string input) {Throw new notimplementedexception ();}
}
Public class convertablestring
{
Private string S;
Public convertablestring (string s) {This. S = s ;}
Public bool isint (string s) {Throw new notimplementedexception ();}
Public bool isdatetime (string s) {Throw new notimplementedexception ();}
Public int toint (string s) {Throw new notimplementedexception ();}
Public datetime todatetime (string s) {Throw new notimplementedexception ();}
}
Public class regexablestring
{
Private string S;
Public regexablestring (string s) {This. S = s ;}
Public bool ismatch (string S, string pattern) {Throw new notimplementedexception ();}
Public String Match (string S, string pattern) {Throw new notimplementedexception ();}
Public String relplace (string S, string pattern, matchevaluator evaluator) {Throw new notimplementedexception ();}
}
You need to introduce this namespace when using it. The reference is as follows:
-
C # code
-
StringStr= "Dafasdf";IntLen=Str. mygetlength ();
Declaration method of the extension method:
1. Static class, static method
2. The first parameter is an instance of the target class. You need to use the this keyword.
For other questions, see. Net 3.0 features. (Use vs2008)