当前位置: 首页 > news >正文

Common方法

一些Common的方法。

 

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Web.Script.Serialization;
  6 using System.IO;
  7 using System.Runtime.Serialization.Json;
  8 using System.Data;
  9 using System.Xml;
 10 using System.Text;
 11 using System.Xml.Serialization;
 12 using System.Reflection;
 13 
 14 namespace Commom
 15 {
 16     public static class CommonMethod
 17     {
 18         public static List<T> JSONStringToList<T>(this string JsonStr)
 19         {
 20             JavaScriptSerializer Serializer = new JavaScriptSerializer();
 21             List<T> objs = Serializer.Deserialize<List<T>>(JsonStr);
 22             return objs;
 23         }
 24 
 25         public static string ConvertToJson(System.Data.DataTable dt)
 26         {
 27             System.Text.StringBuilder retVal = new System.Text.StringBuilder();
 28             retVal.Append("[");
 29             int RowCount = 0, ColumnCount = 0;
 30             foreach (DataRow row in dt.Rows)
 31             {
 32                 RowCount++;
 33                 retVal.Append("{");
 34                 foreach (DataColumn column in dt.Columns)
 35                 {
 36                     ColumnCount++;
 37                     retVal.AppendFormat("'{0}':'{1}'{2}", column.ColumnName, (row[column].ToString()), ColumnCount == dt.Columns.Count ? "" : ",");
 38                 }
 39                 ColumnCount = 0;
 40                 retVal.Append("}");
 41                 retVal.AppendFormat("{0}", RowCount == dt.Rows.Count ? "" : ",");
 42             }
 43             retVal.Append("]");
 44             return retVal.ToString();
 45         }
 46 
 47         public static string ToJSONS(object obj)
 48         {
 49             JavaScriptSerializer serillizer = new JavaScriptSerializer();
 50             return serillizer.Serialize(obj);
 51         }
 52 
 53         public static string ToJSONS(object obj, int recursiondepth)
 54         {
 55             JavaScriptSerializer serialize = new JavaScriptSerializer();
 56             serialize.RecursionLimit = recursiondepth;
 57             return serialize.Serialize(obj);
 58         }
 59 
 60         public static string DtToXml(DataTable dt)
 61         {
 62             if (dt != null)
 63             {
 64                 if (string.IsNullOrEmpty(dt.TableName))
 65                     dt.TableName = Guid.NewGuid().ToString();
 66 
 67                 MemoryStream ms = null;
 68                 XmlTextWriter XmlWt = null;
 69                 try
 70                 {
 71                     ms = new MemoryStream();                   
 72                     XmlWt = new XmlTextWriter(ms, Encoding.Unicode);//根据ms实例化XmlWt                    
 73                     dt.WriteXml(XmlWt);
 74                     int count = (int)ms.Length;
 75                     byte[] temp = new byte[count];
 76                     ms.Seek(0, SeekOrigin.Begin);
 77                     ms.Read(temp, 0, count);                    
 78                     UnicodeEncoding ucode = new UnicodeEncoding();
 79                     string returnValue = ucode.GetString(temp);
 80                     return returnValue;
 81                 }
 82                 catch (System.Exception ex)
 83                 {
 84                     throw ex;
 85                 }
 86                 finally
 87                 {                  
 88                     if (XmlWt != null)//释放资源
 89                     {
 90                         XmlWt.Close();
 91                         ms.Close();
 92                         ms.Dispose();
 93                     }
 94                 }
 95             }
 96             else
 97             {
 98                 return "";
 99             }
100         }
101 
102 
103         public static int ToLength(this string input)
104         {
105             if (input.IsEmpty())
106                 return 0;
107             int n = 0;
108             foreach (char c in input)
109             {
110                 if ((int)c > 256)
111                     n += 2;
112                 else
113                     n++;
114             }
115             return n;
116         }
117 
118         public static bool IsEmpty(this string input)
119         {
120             return string.IsNullOrEmpty(input);
121         }
122 
123 
124         /// <summary>
125         /// 反序列化
126         /// </summary>
127         /// <param name="type">对象类型</param>
128         /// <param name="filename">文件路径</param>
129         public static object Load(Type type, string filename)
130         {
131             FileStream fs = null;
132             try
133             {
134                 // open the stream...
135                 fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
136                 XmlSerializer serializer = new XmlSerializer(type);
137                 return serializer.Deserialize(fs);
138             }
139             catch (Exception ex)
140             {
141                 throw ex;
142             }
143             finally
144             {
145                 if (fs != null)
146                     fs.Close();
147             }
148         }
149 
150         /// <summary>
151         /// 序列化
152         /// </summary>
153         /// <param name="obj">对象</param>
154         /// <param name="filename">文件路径</param>
155         public static void Save(object obj, string filename)
156         {
157             FileStream fs = null;
158             // serialize it...
159             try
160             {
161                 fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
162                 XmlSerializer serializer = new XmlSerializer(obj.GetType());
163                 serializer.Serialize(fs, obj);
164             }
165             catch (Exception ex)
166             {
167                 throw ex;
168             }
169             finally
170             {
171                 if (fs != null)
172                     fs.Close();
173             }
174         }
175 
176     }
177 
178     /// <summary>
179     /// 单例实现辅助类
180     /// </summary>
181     /// <typeparam name="T"></typeparam>
182     public static class Singleton<T> where T : class
183     {
184         static volatile T _instance;
185 
186         static object _lock = new object();
187 
188         static Singleton() { }
189 
190         /// <summary>        
191         /// 创建/获取一个可以new的类对象的单件实例        
192         /// </summary>   
193         public static T Instance
194         {
195             get
196             {
197                 if (_instance == null)
198                 {
199                     lock (_lock)
200                     {
201                         if (_instance == null)
202                         {
203                             ConstructorInfo constructor = null;
204                             try
205                             {
206                                 //构造函数不包含public修饰符的
207                                 constructor = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[0], null);
208                             }
209                             catch (Exception ex)
210                             {
211                                 throw new InvalidOperationException(ex.Message, ex);
212                             }
213                             if (constructor == null || constructor.IsAssembly)
214                             {
215                                 throw new InvalidOperationException(string.Format("在'{0}'里面没有找到private或者protected的构造函数。", typeof(T).Name));
216                             }
217                             _instance = (T)constructor.Invoke(null);
218                         }
219                     }
220                 }
221                 return _instance;
222             }
223         }
224     }
225 
226 
227 }

 

 

 

转载于:https://www.cnblogs.com/bear412/archive/2013/05/07/3065182.html

相关文章:

  • 区块链概况:商业价值
  • 【水】tyvj1523 平面几何入门
  • web标准化(下)
  • Java环境搭建与配置
  • 【JS第17期】单体内置对象
  • Delphi编程地一些小程序
  • 乐观锁和悲观锁
  • Linux初始设置
  • PostgreSQL 11 preview - 分页内核层优化 - 索引扫描offset优化(使用vm文件skip heap scan)...
  • linux下jdb远程调试tomcat源码
  • PostgreSQL 11 preview - pgbench 支持大于1000链接(ppoll()代替select())
  • 数字操作符九度OJ 1019 简单计算器
  • NO1 ip-systemctl-fdisk
  • 执行对象cocos2d-x 2.x action动作整理集合
  • MySQL主从复制介绍
  • Android单元测试 - 几个重要问题
  • CSS3 聊天气泡框以及 inherit、currentColor 关键字
  • iOS | NSProxy
  • Javascript弹出层-初探
  • JavaWeb(学习笔记二)
  • leetcode-27. Remove Element
  • PAT A1017 优先队列
  • Python学习之路16-使用API
  • swift基础之_对象 实例方法 对象方法。
  • thinkphp5.1 easywechat4 微信第三方开放平台
  • vagrant 添加本地 box 安装 laravel homestead
  • 编写符合Python风格的对象
  • 从tcpdump抓包看TCP/IP协议
  • 第三十一到第三十三天:我是精明的小卖家(一)
  • 分类模型——Logistics Regression
  • 经典排序算法及其 Java 实现
  • k8s使用glusterfs实现动态持久化存储
  • ​LeetCode解法汇总1276. 不浪费原料的汉堡制作方案
  • ​力扣解法汇总1802. 有界数组中指定下标处的最大值
  • !!java web学习笔记(一到五)
  • # Panda3d 碰撞检测系统介绍
  • # 数论-逆元
  • # 学号 2017-2018-20172309 《程序设计与数据结构》实验三报告
  • #includecmath
  • $分析了六十多年间100万字的政府工作报告,我看到了这样的变迁
  • (16)Reactor的测试——响应式Spring的道法术器
  • (C++20) consteval立即函数
  • (floyd+补集) poj 3275
  • (Redis使用系列) Springboot 使用Redis+Session实现Session共享 ,简单的单点登录 五
  • (分类)KNN算法- 参数调优
  • (附源码)springboot高校宿舍交电费系统 毕业设计031552
  • (深入.Net平台的软件系统分层开发).第一章.上机练习.20170424
  • (一)Linux+Windows下安装ffmpeg
  • (原創) 未来三学期想要修的课 (日記)
  • .cn根服务器被攻击之后
  • .gitignore文件设置了忽略但不生效
  • .java 9 找不到符号_java找不到符号
  • .NET 5种线程安全集合
  • .NET C# 使用 SetWindowsHookEx 监听鼠标或键盘消息以及此方法的坑
  • .NET/C# 使用 #if 和 Conditional 特性来按条件编译代码的不同原理和适用场景