Defines a static class in which static methods are defined, and method extensions to parameter types are implemented by adding the This modifier to the parameter types in the methods
Examples such as namespace Demo{
//The class here must be a static class Public Static classJson {
//method is a static method
The //This modifier is followed by a string type that extends the Tojson method for the string type Public Static ObjectToJson ( This stringJson) { returnJson = =NULL?NULL: Jsonconvert.deserializeobject (Json); }
The This modifier is followed by type object, which extends the Tojson method for the object type Public Static stringToJson ( This Objectobj) { varTimeConverter =Newisodatetimeconverter {DateTimeFormat ="YYYY-MM-DD HH:mm:ss" }; returnjsonconvert.serializeobject (obj, timeconverter); } Public Static stringToJson ( This ObjectObjstringdatetimeformats) { varTimeConverter =Newisodatetimeconverter {DateTimeFormat =Datetimeformats}; returnjsonconvert.serializeobject (obj, timeconverter); } Public StaticT toobject<t> ( This stringJson) { returnJson = =NULL?default(T): jsonconvert.deserializeobject<t>(Json); } Public StaticList<t> tolist<t> ( This stringJson) { returnJson = =NULL?NULL: jsonconvert.deserializeobject<list<t>>(Json); } Public StaticDataTable ToTable ( This stringJson) { returnJson = =NULL?NULL: jsonconvert.deserializeobject<datatable>(Json); } Public StaticJobject Tojobject ( This stringJson) { returnJson = =NULL? Jobject.parse ("{}"): Jobject.parse (Json.replace (" ","")); } } Public classUser { Public stringID {Get;Set; } Public stringCode {Get;Set; } Public stringName {Get;Set; } } classProgram {Static voidMain (stringTry{List<User> users =NewList<user>NewUser{id="1", code="ZS", name="Zhang San"}, NewUser{id="2", code="ls", name="John Doe"} }; //The list is extended with the Tojson method for converting strings stringJSON =users. ToJson (); //The string type is extended out of the Tojson method for converting objects Objectobj =JSON. ToJson (); //The string type is extended to the ToList method, which is used to convert the listUsers = json. Tolist<user>();
Convert a DataTable to a string type
DataTable Dt=json. ToTable ();
} Catch(Exception ex) {Console.WriteLine (ex); } finally{console.readline (); } } }}
Next, share the indexer usage of this keyword
C # This usage series (ii) extending methods for primitive types through the This modifier