zoukankan      html  css  js  c++  java
  • C# 用this修饰符为原始类型扩展方法

    特点:1、静态类 2、静态方法 3、第一个参数前加this

    例如:public static List<T> ToList<T>(this string Json),就是为this对应的string类型扩展类ToList()方法,调用方式 strJson.ToList();

    详细扩展

    namespace Demo
    {
        public static class Extends
        {
         // string类型扩展ToJson方法
    public static object ToJson(this string Json) { return Json == null ? null : JsonConvert.DeserializeObject(Json); } // object类型扩展ToJson方法 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;", "")); } } class Program { static void Main(string[] args) { try { List<User> users = new List<User>{ new User{ID="1",Code="zs",Name="张三"}, new User{ID="2",Code="ls",Name="李四"} }; // list转化json字符串 string json = users.ToJson();           // string转化List users = json.ToList<User>(); // string转化DataTable DataTable dt = json.ToTable(); } catch (Exception ex) { Console.WriteLine(ex); } finally { Console.ReadLine(); } } } public class User { public string ID { get; set; } public string Code { get; set; } public string Name { get; set; } } }
  • 相关阅读:
    sublime显示当前文件的编码格式
    关于jquery中html()、text()、val()的区别
    bit,Byte,B,KB,MB,GB
    python之序列操作
    编程常用密匙
    js数组操作
    ob函数的使用
    php使用zlib实现gzip压缩
    js兼容性汇总
    centos7下源码编译安装mysql5.7
  • 原文地址:https://www.cnblogs.com/jh007/p/6122585.html
Copyright © 2011-2022 走看看