C # Feature extension methods
Primarily for generic collections and generic classes
The nature of the extension method: Compile-time, directly to Str. Writeself (2015) replaced with stringutil.writeself (STR,2015);
What if you want to add some members to a type?
Extension methods:
classProgram {Static voidMain (string[] args) { stringstr ="2015-01-01"; //calling a static methodDateTime Resualt =Str. Totry (DateTime.Now); Console.Write (Resualt); Console.Write (Resualt. GetType ()); Console.readkey (); } } /// <summary> ///extension method Static class/// </summary> Public Static classConverttotype {/// <summary> ///extension method Keyword this/// </summary> /// <param name= "value" >types to be transferred</param> /// <returns>returns 0 by default</returns> Public Static intTotry ( This stringvalue) { inttemp =0; if(!string. IsNullOrEmpty (value)) {Try { int. TryParse (Value, outtemp); } Catch{Temp=0; } } returntemp; } /// <summary> ///Data type Conversions/// </summary> /// <typeparam name= "T" ></typeparam> /// <param name= "value" ></param> /// <param name= "DefaultValue" ></param> /// <returns></returns> Public StaticT totry<t> ( This Objectvalue, T defaultvalue) { //1 Determining type of T 2 type of Object//one problem that arises in generic classes and generic methods is how to assign a default value to a parameterized type T when the following conditions are not known in advance://The DEFAULT keyword returns null if T is a reference type, and the value type returns 0,null return System.Nullable (Of T) ObjectStartvalue =default(T); if(Value! =NULL) { //typeof and GetType () differences//typeof for Type//GetType for type instantiation//Test t=new Test () T.gettype () and typeof (T) Try{Type Converttype=typeof(T); if(Converttype = =typeof(String)) {Startvalue=value. ToString (); } if(Converttype = =typeof(Int32)) {Startvalue=Convert.ToInt32 (value); } if(Converttype = =typeof(DateTime)) {Startvalue=convert.todatetime (value); } return(T) Startvalue; } Catch { returnDefaultValue; } } Else { returnDefaultValue; } } }
1. ASP. NET MVC Introduction to Mastery--new grammar