当前位置: 移动技术网 > IT编程>开发语言>.net > C# Common utils

C# Common utils

2019年02月19日  | 移动技术网IT编程  | 我要评论

小老乡进城,亚信男,强心脏110712

对象深拷贝

 1 /// <summary>
 2 /// 深度克隆对象
 3 /// </summary>
 4 /// <typeparam name="t">待克隆类型(必须由[serializable]修饰)</typeparam>
 5 /// <param name="obj">待克隆对象</param>
 6 /// <returns>新对象</returns>
 7 public static t clone<t>(t obj)
 8 {
 9     t ret = default(t);
10     if (obj != null)
11     {
12         xmlserializer cloner = new xmlserializer(typeof(t));
13         memorystream stream = new memorystream();
14         cloner.serialize(stream, obj);
15         stream.seek(0, seekorigin.begin);
16         ret = (t)cloner.deserialize(stream);
17     }
18     return ret;
19 }
20 /// <summary>
21 /// 克隆对象
22 /// </summary>
23 /// <param name="obj">待克隆对象(必须由[serializable]修饰)</param>
24 /// <returns>新对象</returns>
25 public static object cloneobject(object obj)
26 {
27     using (memorystream memstream = new memorystream())
28     {
29         binaryformatter binaryformatter = new binaryformatter(null,new streamingcontext(streamingcontextstates.clone));
30         binaryformatter.serialize(memstream, obj);
31         memstream.seek(0, seekorigin.begin);
32         return binaryformatter.deserialize(memstream);
33     }
34 }

 计算最大公约数

 1 /// <summary>
 2 /// 计算最大公约数
 3 /// </summary>
 4 /// <param name="a">数值a</param>
 5 /// <param name="b">数值b</param>
 6 /// <returns>最大公约数</returns>
 7 private static ulong gcd(ulong a, ulong b)
 8 {
 9     return b == 0 ? a : gcd(b, a % b);
10 }

 数组与结构体相互转换

 1 /// <summary>
 2 /// uds报文结构体(示例)
 3 /// </summary>
 4 [structlayoutattribute(layoutkind.sequential, charset = charset.ansi, pack = 1)]
 5 public struct stdudsmsg
 6 {
 7     public byte dl;
 8     public byte sid;
 9     [marshalas(unmanagedtype.byvalarray, sizeconst = 2)]
10     public byte[] did;
11     [marshalas(unmanagedtype.byvalarray, sizeconst = 4)]
12     public byte[] data;
13 }
14 /// <summary>
15 /// byte 数组转结构体
16 /// </summary>
17 /// <typeparam name="t">结构体对象类型</typeparam>
18 /// <param name="bytes">byte 数组</param>
19 /// <returns>结构体对象</returns>
20 public t bytearraytostructure<t>(byte[] bytes) where t : struct
21 {
22     t stuff = new t();
23     gchandle handle = gchandle.alloc(bytes, gchandletype.pinned);
24     try
25     {
26         stuff = (t)marshal.ptrtostructure(handle.addrofpinnedobject(), typeof(t));
27     } finally
28     {
29         handle.free();
30     }
31     return stuff;
32 }
33 /// <summary>
34 /// 结构体对象转 byte 数组
35 /// </summary>
36 /// <typeparam name="t">结构体对象类型</typeparam>
37 /// <param name="stuff">结构体对象</param>
38 /// <returns>数组</returns>
39 public byte[] structuretobytearray<t>(t stuff) where t : struct
40 {
41     int size = 0;
42     intptr? msgptr = null;
43     byte[] resbuf = null;
44     try
45     {
46         size = marshal.sizeof(stuff);
47         resbuf = new byte[size];
48         msgptr = marshal.allochglobal(size);
49         marshal.structuretoptr(stuff, msgptr.value, false);
50         marshal.copy(msgptr.value, resbuf, 0, size);
51     } finally
52     {
53         if (msgptr != null)
54         {
55             marshal.freehglobal(msgptr.value);
56         }
57     }
58     return resbuf;
59 }

 字符串与char数组、byte数组转换

 1 /// <summary>
 2 /// 将char数组空余部分填充默认值
 3 /// </summary>
 4 /// <param name="data">目标char数组</param>
 5 /// <param name="deflength">数组总长度</param>
 6 /// <returns>空余部分被填充默认值的新数组</returns>
 7 public static char[] extarrayfill(this char[] data, int deflength)
 8 {
 9     deflength = deflength - data.length;
10     char[] dchararray = new char[deflength];
11     int i = 0;
12     while (i < deflength)
13     {
14         dchararray[i++] = '\0';
15     }
16     char[] nchararray = new char[data.length + deflength];
17     array.copy(data, 0, nchararray, 0, data.length);
18     array.copy(dchararray, 0, nchararray, data.length, deflength);
19     return nchararray;
20 }
21 /// <summary>
22 /// 将string转为byte[],并填充默认值\0
23 /// </summary>
24 /// <param name="data">string数据</param>
25 /// <param name="deflength">长度</param>
26 /// <returns>填充后的bytre[]</returns>
27 public static char[] extarrayfill(this string data, int deflength)
28 {
29     deflength = deflength - data.length;
30     char[] def = new char[deflength];
31     int i = 0;
32     while (i < deflength)
33     {
34         def[i++] = '\0';
35     }
36     string defstr = new string(def);
37     string nstr = data + defstr;
38 
39     return nstr.tochararray();
40 }
41 /// <summary>
42 /// 将gb2312编码string转为char[],并填充默认值
43 /// </summary>
44 /// <param name="data">string数据</param>
45 /// <param name="deflength">长度</param>
46 /// <returns>填充后的bytre[]</returns>
47 public static byte[] extarrayfillgb2312(this string data, int deflength) {
48     byte[] tmpbuf = new byte[deflength];
49     for (int i = 0; i < deflength; i++) {
50         tmpbuf[i] = 0;
51     }
52     encoding gb2312 = encoding.getencoding("gb2312");
53     byte[] tmpdatabuf = gb2312.getbytes(data);
54     for (int i = 0; i < tmpdatabuf.length; i++) {
55         if (tmpdatabuf.length >= deflength)
56             break;
57         tmpbuf[i] = tmpdatabuf[i];
58     }
59     return tmpbuf;
60 }

 windows消息处理

 1 struct copydatastruct
 2 {
 3     public intptr dwdata;
 4     public int cbdata;
 5     [marshalas(unmanagedtype.lpstr)]
 6     public string lpdata;
 7 }
 8 /// <summary>
 9 /// windows消息处理辅助工具类
10 /// </summary>
11 public static class messageutils
12 {
13     const int wm_copydata = 0x004a;
14 
15     [dllimport("user32.dll", entrypoint = "sendmessage")]
16     private static extern int sendmessage(int hwnd, int msg, int wparam, ref copydatastruct lparam);
17 
18     [dllimport("user32.dll", entrypoint = "findwindow")]
19     private static extern int findwindow(string lpclassname, string lpwindowname);
20     /// <summary>
21     /// 发布wm_copydata消息
22     /// </summary>
23     /// <param name="strwindowname">进程窗体title</param>
24     /// <param name="idata">ushort自定义数据</param>
25     /// <param name="strdata">string自定义数据</param>
26     /// <returns></returns>
27     public static bool sendcopydata(string strwindowname, ushort idata, string strdata)
28     {
29         int hwnd = findwindow(null, strwindowname);
30         if (hwnd == 0)
31         {
32             return false;
33         }
34         else
35         {
36             byte[] sarr = system.text.encoding.ascii.getbytes(strdata);
37             int len = sarr.length;
38             copydatastruct cds;
39             cds.dwdata = (intptr)convert.toint16(idata);//任意值
40             cds.cbdata = len + 1;//
41             cds.lpdata = strdata;
42             sendmessage(hwnd, wm_copydata, 0, ref cds);
43             return true;
44         }
45     }
46 }

 字符串编码转换

 1 /// <summary>
 2 /// gb2312编码字符串转utf-8编码字符串
 3 /// </summary>
 4 /// <param name="strgb2312">gb2312编码字符串</param>
 5 /// <returns>utf-8编码字符串</returns>
 6 public static string gb2312toutf8(string strgb2312) {
 7     encoding gb2312 = encoding.getencoding("gb2312");
 8     byte []gbbuf=gb2312.getbytes(strgb2312);
 9     encoding utf8 = encoding.getencoding("utf-8");
10     byte[] u8buf = null;
11     u8buf = encoding.convert(gb2312, utf8, gbbuf);
12     string strutf8 = utf8.getstring(u8buf);
13     return strutf8;
14 }
15 /// <summary>
16 /// gb2312编码byte数组转utf-8编码字符串
17 /// </summary>
18 /// <param name="gb2312buf">gb2312数组</param>
19 /// <returns>utf8数组</returns>
20 public static string gb2312toutf8(byte[] gb2312buf) {
21     encoding gb2312 = encoding.getencoding("gb2312");
22     string strgb = gb2312.getstring(gb2312buf);
23     return gb2312toutf8(strgb);
24 }
25 /// <summary>
26 /// 字符串字符集编码转换
27 /// </summary>
28 /// <param name="srcencodingname">源字符集</param>
29 /// <param name="dstencodingname">目标字符集</param>
30 /// <param name="srcstring">源字符集编码字符串</param>
31 /// <returns>生成目标字符集编码字符串</returns>
32 public static string strconvert(string srcencodingname, string dstencodingname, string srcstring) {
33     encoding srcencoding = encoding.getencoding(srcencodingname);
34     byte[] srcbuf = srcencoding.getbytes(srcstring);
35     encoding dstencoding = encoding.getencoding(dstencodingname);
36     byte[] dstbuf = null;
37     dstbuf = encoding.convert(srcencoding, dstencoding, srcbuf);
38     string strdest = dstencoding.getstring(dstbuf);
39     return strdest;
40 }
41 /// <summary>
42 /// gb2312编码字符串转utf-8编码字符串
43 /// </summary>
44 /// <param name="strgb2312">gb2312编码字符串</param>
45 /// <returns>utf-8编码字符串</returns>
46 public static string gb2312toutf8ex(this string strgb2312) {
47     return gb2312toutf8(strgb2312);
48 }
49         
50 
51 /// <summary>
52 /// 字符串字符集编码转换
53 /// </summary>
54 /// <param name="srcencodingname">源字符集</param>
55 /// <param name="dstencodingname">目标字符集</param>
56 /// <param name="srcstring">源字符集编码字符串</param>
57 /// <returns>生成目标字符集编码字符串</returns>
58 public static string strconvertex(this string srcstring, string srcencodingname, string dstencodingname) {
59     return strconvert(srcencodingname, dstencodingname, srcstring);
60 }

通过反射获取对象所有属性集合,以键值对形式展现

 1 /// <summary>
 2 /// 获取对象所有属性键值对
 3 /// </summary>
 4 /// <typeparam name="t">对象类型</typeparam>
 5 /// <param name="t">目标对象</param>
 6 /// <returns>对象键值对集</returns>
 7 public dictionary<string, object> getobjproperties<t>(t t)
 8 {
 9     dictionary<string, object> res = new dictionary<string, object>();
10     if (t == null)
11     {
12         return null;
13     }
14     var properties = t.gettype().getproperties(system.reflection.bindingflags.instance | system.reflection.bindingflags.public);
15 
16     if (properties.length <= 0)
17     {
18         return null;
19     }
20     foreach (var item in properties)
21     {
22         string name = item.name;
23         object value = item.getvalue(t, null);
24         if (item.propertytype.isvaluetype || item.propertytype.name.startswith("string"))
25         {
26             res.add(name, value);
27         } else
28         {
29             getobjproperties(value);
30         }
31     }
32     return res;
33 }

 实体类转sql条件字符串

 1 /// <summary>
 2 /// 实体类转sql条件,实体类参数中值为null的属性不参与sql生成,故此,本函数不支持null查询
 3 /// </summary>
 4 /// <typeparam name="t">实体类对象类型</typeparam>
 5 /// <param name="entity">作为查询条件的实体类</param>
 6 /// <param name="logicoperator">各属性间逻辑运算符(如and,or)</param>
 7 /// <returns>sql条件字符串</returns>
 8 public string entitytosqlcondition<t>(t entity, string logicoperator)
 9 {
10     if (entity == null)
11     {
12         return null;
13     }
14     var properties = entity.gettype()
15         .getproperties(system.reflection.bindingflags.instance | system.reflection.bindingflags.public)
16         .asenumerable().where(p => p.getvalue(entity, null) != null);
17 
18     if (properties.count() <= 0)
19     {
20         return null;
21     }
22     stringbuilder sbcondition = new stringbuilder(" ");
23     int index = 0;
24     foreach (var item in properties)
25     {
26         string name = item.name;
27         object value = item.getvalue(entity, null);
28         if (index != properties.count() - 1)
29         {
30             if (item.propertytype.isvaluetype)
31             {
32                 sbcondition.appendformat("{0}={1} {2} ", name, value, logicoperator);
33             } else if (item.propertytype.name.startswith("string"))
34             {
35                 sbcondition.appendformat("{0}='{1}' {2} ", name, value, logicoperator);
36             }
37         } else
38         {
39             if (item.propertytype.isvaluetype)
40             {
41                 sbcondition.appendformat(" {0}={1} ", name, value);
42             } else if (item.propertytype.name.startswith("string"))
43             {
44                 sbcondition.appendformat(" {0}='{1}' ", name, value);
45             }
46         }
47         index++;
48     }
49     return sbcondition.tostring();
50 }

 

 

待续

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网