泛型+反射 List<任意类型>序列化+反序列化

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();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值