/******************************************************************** 文件: PackReflectionEntity.cs 作者: 梦语 邮箱: 1982614048@qq.com 创建时间: 2024/03/29 17:28:19 最后修改: 梦语 最后修改时间: 2024/04/03 16:00:00 功能: 类和文本字符串相互转换 *********************************************************************/ using System; using System.Reflection; using System.Collections.Generic; using System.Text; namespace Ether { public class PackReflectionEntity { /// /// 类转文本字符串 /// /// 实例类 /// public static string GetEntityToString(T t) { StringBuilder sb = new StringBuilder(); Type type = t.GetType(); PropertyInfo[] propertyInfos = type.GetProperties(); for (int i = 0; i < propertyInfos.Length; i++) { sb.Append(propertyInfos[i].Name + " = " + propertyInfos[i].GetValue(t, null) + "\n"); } return sb.ToString().TrimEnd(new char[] { '\n' }); } /// /// 文本字符串转类 /// /// /// public static T GetEntityStringToEntity(string[] array) { string[] temp = null; Dictionary dic = new Dictionary(); foreach (string s in array) { string arr = s.Replace(" ", ""); temp = arr.Split('='); dic.Add(temp[0], temp[1]); } Assembly assembly = Assembly.GetAssembly(typeof(T)); T entry = (T)assembly.CreateInstance(typeof(T).FullName); StringBuilder sb = new StringBuilder(); Type type = entry.GetType(); PropertyInfo[] propertyInfos = type.GetProperties(); for (int i = 0; i < propertyInfos.Length; i++) { foreach (string key in dic.Keys) { if (propertyInfos[i].Name == key.ToString()) { propertyInfos[i].SetValue(entry, GetObject(propertyInfos[i], dic[key]), null); break; } } } return entry; } /// /// 文本字符串转类(重载) /// /// 字符串 /// public static T GetEntityStringToEntity(string str) { string[] array = str.Split('\n'); return GetEntityStringToEntity(array); } /// /// 获取类型 /// /// private static object GetObject(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; } } } }