這篇文章主要介紹了C#實現實體類與字符串互相轉換的方法,涉及C#字符串及對象的相互轉換技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了C#實現實體類與字符串互相轉換的方法。分享給大家供大家參考。具體實現方法如下:
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace PackDLL.Data.ConvertData
- {
- /// <summary>
- /// 實體類、字符串互相轉換
- /// </summary>
- public class PackReflectionEntity<T>
- {
- /// <summary>
- /// 將實體類通過反射組裝成字符串
- /// </summary>
- /// <param name="t">實體類</param>
- /// <returns>組裝的字符串</returns>
- public static string GetEntityToString(T t)
- {
- System.Text.StringBuilder sb = new StringBuilder();
- Type type = t.GetType();
- System.Reflection.PropertyInfo[] propertyInfos = type.GetProperties();
- for (int i = 0; i < propertyInfos.Length; i++)
- {
- sb.Append(propertyInfos[i].Name + ":" + propertyInfos[i].GetValue(t, null) + ",");
- }
- return sb.ToString().TrimEnd(new char[] { ',' });
- }
- /// <summary>
- /// 將反射得到字符串轉換為對象
- /// </summary>
- /// <param name="str">反射得到的字符串</param>
- /// <returns>實體類</returns>
- public static T GetEntityStringToEntity(string str)
- {
- string[] array = str.Split(',');
- string[] temp = null;
- Dictionary<string, string> dictionary = new Dictionary<string, string>();
- foreach (string s in array)
- {
- temp = s.Split(':');
- dictionary.Add(temp[0], temp[1]);
- }
- System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(T));
- T entry = (T)assembly.CreateInstance(typeof(T).FullName);
- System.Text.StringBuilder sb = new StringBuilder();
- Type type = entry.GetType();
- System.Reflection.PropertyInfo[] propertyInfos = type.GetProperties();
- for (int i = 0; i < propertyInfos.Length; i++)
- {
- foreach (string key in dictionary.Keys)
- {
- if (propertyInfos[i].Name == key.ToString())
- {
- propertyInfos[i].SetValue(entry, GetObject(propertyInfos[i], dictionary[key]), null);
- break;
- }
- }
- }
- return entry;
- }
- /// <summary>
- /// 轉換值的類型
- /// </summary>
- /// <param name="p"></param>
- /// <param name="value"></param>
- /// <returns></returns>
- static object GetObject(System.Reflection.PropertyInfo p, string value)
- {
- switch (p.PropertyType.Name.ToString().ToLower())
- {
- case "int16":
- return Convert.ToInt16(value);
- case "int32":
- return Convert.ToInt32(value);
- case "int64":
- return Convert.ToInt64(value);
- case "string":
- return Convert.ToString(value);
- case "datetime":
- return Convert.ToDateTime(value);
- case "boolean":
- return Convert.ToBoolean(value);
- case "char":
- return Convert.ToChar(value);
- case "double":
- return Convert.ToDouble(value);
- default:
- return value;
- }
- }
- }
- }
希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答