Usage series of this in C (2) Extending methods for original types through this modifiers

  • 2021-11-13 02:30:33
  • OfStack

Define a static class, define a static method in the class, and add this modifier in front of the parameter type in the method to realize the method extension of the parameter type

For example


namespace Demo{
//  The class here must be static 
public static class Json
{
       //  Method is static 
// this Modifier is followed by string Type, that is, string Type extends out of ToJson Method 
public static object ToJson(this string Json)
{
return Json == null ? null : JsonConvert.DeserializeObject(Json);
}
       // this Modifier followed by a type of object, That is object Type extends out of ToJson Method 
public static string ToJson(this object obj)
{
var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
return JsonConvert.SerializeObject(obj, timeConverter);
}
public static string ToJson(this object obj, string datetimeformats)
{
var timeConverter = new IsoDateTimeConverter { DateTimeFormat = datetimeformats };
return JsonConvert.SerializeObject(obj, timeConverter);
}
public static T ToObject<T>(this string Json)
{
return Json == null ? default(T) : JsonConvert.DeserializeObject<T>(Json);
}
public static List<T> ToList<T>(this string Json)
{
return Json == null ? null : JsonConvert.DeserializeObject<List<T>>(Json);
}
public static DataTable ToTable(this string Json)
{
return Json == null ? null : JsonConvert.DeserializeObject<DataTable>(Json);
}
public static JObject ToJObject(this string Json)
{
return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace("&nbsp;", ""));
}
}
public class User {
public string ID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(stringtry
{
List<User> users = new List<User>new User{ID="1",Code="zs",Name=" Zhang 3"},
new User{ID="2",Code="ls",Name=" Li 4"}
};
// List Has been extended ToJson Method to convert a string 
string json = users.ToJson();
// string The type has been extended ToJson Method for converting objects 
object obj = json.ToJson();
// string The type has been extended ToList Method for converting List
users = json.ToList<User>();
                
                // string Type conversion DataTable
                DataTable dt=json.ToTable();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
Console.ReadLine();
}
}
}
}

Related articles: