Summary:. Net has two methods for class Extension: one is extension method and the other is partial classification;
Extension Method:
In C #. net, you can customize extension classes, that is, to extend some ready-made classes or classes without source code.
The extension method allows you to extend an existing type and add its method without inheriting it or re-compiling it. Unlike the object write assistant method, the extension method can be a part of the object itself. An extension method is a static method defined in a static class and must have a parameter pointing to the type object attached to the method.
For example, if we want to verify whether a string (which already exists and has no source code) is a valid email address, we can compile a method, enter it as a string, and return true or false. Now we can use the extension method as follows:
Public static class myextensions {
Public static bool isvalidemailaddress (this string s ){
RegEx = new RegEx (@ "^ [w-.] + @ ([w-] +.) + [w-] {2, 4} $ ");
Return RegEx. ismatch (s );
}
}
We define a static class with a static method. Note that the static method has a this keyword before the parameter type string, which tells the compiler that this special extension method will be added to the string type object. So we can call this member method in string:
Using myextensions;
String email = request. querystring ["email"];
If (email. isvalidemailaddress ()){
//...
}
Of course, in addition to the method in this example, if you add partial before the class, you can directly name the same class in another file to add the method you need.
For example:
Namespace PC
{
Partial Class {}
}
Namespace PC
{
Partial Class {}
}
These two classes are actually a class. In this way, the automatically generated code is separated from the self-compiled code. Easy code control.