C#实现实体类与字符串互相转换的方法

2019-12-26 13:17:07王旭

易采站长站为您分析C#实现实体类与字符串互相转换的方法,涉及C#字符串及对象的相互转换技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了C#实现实体类与字符串互相转换的方法。。具体实现方法如下:

 

 
  1. using System;  using System.Collections.Generic; 
  2. using System.Text;  namespace PackDLL.Data.ConvertData 
  3. {  /// <summary> 
  4. /// 实体类、字符串互相转换  /// </summary> 
  5. public class PackReflectionEntity<T>  { 
  6. /// <summary>  /// 将实体类通过反射组装成字符串 
  7. /// </summary>  /// <param name="t">实体类</param> 
  8. /// <returns>组装的字符串</returns>  public static string GetEntityToString(T t) 
  9. {  System.Text.StringBuilder sb = new StringBuilder(); 
  10. Type type = t.GetType();  System.Reflection.PropertyInfo[] propertyInfos = type.GetProperties(); 
  11. for (int i = 0; i < propertyInfos.Length; i++)  { 
  12. sb.Append(propertyInfos[i].Name + ":" + propertyInfos[i].GetValue(t, null) + ",");  } 
  13. return sb.ToString().TrimEnd(new char[] { ',' });  } 
  14. /// <summary>  /// 将反射得到字符串转换为对象 
  15. /// </summary>  /// <param name="str">反射得到的字符串</param> 
  16. /// <returns>实体类</returns>  public static T GetEntityStringToEntity(string str) 
  17. {  string[] array = str.Split(','); 
  18. string[] temp = null;  Dictionary<string, string> dictionary = new Dictionary<string, string>(); 
  19. foreach (string s in array)  { 
  20. temp = s.Split(':');  dictionary.Add(temp[0], temp[1]); 
  21. }  System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(typeof(T));