對象深拷貝 計算最大公約數 數組與結構體相互轉換 字元串與char數組、byte數組轉換 Windows消息處理 字元串編碼轉換 通過反射獲取對象所有屬性集合,以鍵值對形式展現 實體類轉SQL條件字元串 待續 ...
對象深拷貝
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 }
待續