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

2019-12-26 13:17:07王旭
  • 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;  } 
  • }  }