欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#實(shí)現(xiàn)實(shí)體類與字符串互相轉(zhuǎn)換的方法

 更新時(shí)間:2015年08月22日 12:43:14   作者:我心依舊  
這篇文章主要介紹了C#實(shí)現(xiàn)實(shí)體類與字符串互相轉(zhuǎn)換的方法,涉及C#字符串及對(duì)象的相互轉(zhuǎn)換技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下

本文實(shí)例講述了C#實(shí)現(xiàn)實(shí)體類與字符串互相轉(zhuǎn)換的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:

using System;
using System.Collections.Generic;
using System.Text;
namespace PackDLL.Data.ConvertData
{
 /// <summary>
 /// 實(shí)體類、字符串互相轉(zhuǎn)換
 /// </summary>
 public class PackReflectionEntity<T>
 {
  /// <summary>
  /// 將實(shí)體類通過反射組裝成字符串
  /// </summary>
  /// <param name="t">實(shí)體類</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>
  /// 將反射得到字符串轉(zhuǎn)換為對(duì)象
  /// </summary>
  /// <param name="str">反射得到的字符串</param>
  /// <returns>實(shí)體類</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>
  /// 轉(zhuǎn)換值的類型
  /// </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;
   }
  }
 }
}

希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論