C # provides a very practical way to provide energy, extension methods (Extension method)
The extension method is to extend an existing type by an additional static method. By extending the method, you can do the related extensions you want to do with the existing types. Method: Defines a static class, the extension method is also a static method, and the first parameter of the extension method is the type to be extended, a This keyword must be attached.
examples are as follows:
Extension classes:
Public Static classExtend { Public Static BOOLIsNullOrEmpty ( This Objecti) {if(i = =NULL)return true; if(I.gettype () = =typeof(string)) { stringtemp = (string) I; returntemp. IsNullOrEmpty (); } Else return false; } Public StaticGuid Toguid ( This stringi) {Guid id; if(! Guid.tryparse (I, outid)) {Throw NewException (i +"can not is converted to Guid"); } returnID; } }
Extension method Invocation:
public class Testextend { public void Test () { string i = " this a World for me " try {GUID GUID = I.toguid (); Console.Write (GUID. ToString ()); catch (Exception ex) { Console.WriteLine (ex. Message); } } }
C # Extension Classes