using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
namespace CFrame.CFrame
{
//CLine 类型字符串简介 如下
//值a1,值b1,值c1__值a2,值b2,值c2_值a3,值b3,值c3
//1,mike,12_2,scott,16_3,puck,18_4,bob,21
//既然要传输字符串必然知道它有哪些属性,所以不需要带属性
public static class CLine
{
public static string List2CLine<T>(List<T> l)
{
string s = "";
PropertyInfo[] p = typeof(T).GetProperties();
for (int i = 0; i <= p.Length - 1; i++)
{
if (i == p.Length - 1)
{
s += p[i].Name + "_";
break;
}
s += p[i].Name + ",";
}
for (int i = 0; i <= l.Count - 1; i++)
{
for (int j = 0; j <= p.Length - 1; j++)
{
if (j == p.Length - 1)
{
if (i == l.Count - 1)
{
s += p[j].GetValue(l[i], null).ToString();
break;
}
else
{
s += p[j].GetValue(l[i], null).ToString() + "_";
break;
}
}
s += p[j].GetValue(l[i], null).ToString() + ",";
}
}
return s;
} //序列化任何类型的 List 为 CLine类型的字符串
public static List<T> CLine2List<T>(string s)//反序列化 CLine 类型的字符串为对应类型的 List
{
List<T> l = new List<T>();
string[] lstr = s.Split('_');
PropertyInfo[] p = typeof(T).GetProperties();
for (int i = 0; i <= lstr.Length - 1; i++)
{
string[] tstr = lstr[i].Split(',');
var t = Assembly.Load(typeof(T).Assembly.GetName()).CreateInstance(typeof(T).FullName);
for (int j = 0; j <= tstr.Length - 1; j++)
{
p[j].SetValue(t, Convert.ChangeType(tstr[j], p[j].PropertyType), null);
}
l.Add((T)t);
}
return l.ToList();
}
}
}
泛型+反射 List<任意类型>序列化+反序列化
最新推荐文章于 2024-08-09 13:45:00 发布