国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#實現實體類與字符串互相轉換的方法

2020-01-24 01:30:46
字體:
來源:轉載
供稿:網友

本文實例講述了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#程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 邯郸市| 开化县| 鄂伦春自治旗| 天柱县| 维西| 新平| 江源县| 清涧县| 通江县| 浏阳市| 泉州市| 湄潭县| 牙克石市| 开江县| 堆龙德庆县| 新乡市| 沐川县| 庆云县| 海伦市| 兰西县| 焉耆| 枣阳市| 蕲春县| 禄丰县| 黄骅市| 金川县| 星座| 图片| 大同市| 霍邱县| 洞口县| 丹棱县| 伊川县| 固始县| 宁化县| 衡水市| 延寿县| 牡丹江市| 出国| 吴桥县| 正宁县|