C# 类对象数据存储(Object自定义序列化)

42 篇文章 0 订阅
1 篇文章 0 订阅

获取Object对象的所有成员变量:

FieldInfo[] fields = obj.GetType().GetFields();    // obj可以为任意类型对象

获取变量名称:

string name = field.Name;

 获取变量值:

Object valueObj = field.GetValue(obj);

设置obj中指定变量的值:

string value = "123";

Type type = field.FieldType;
object valueObj = Convert.ChangeType(value, type);  // 转化为变量对应类型

field.SetValue(obj, valueObj);                      // 设置值

类对象数据存储示例:


 源码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace SciTools
{
    public class OrderParam
    {
        public string orderId = "";
        public string param = "";
        public int count = 0;


        #region 类对象逻辑

        public OrderParam(string orderId = "", string param = "", int count = 0)
        {
            this.orderId = orderId;
            this.param = param;
            this.count = count;
        }

        /// <summary>
        /// 从data数据构建OrderParam
        /// </summary>
        public static OrderParam Parse(string data)
        {
            OrderParam I = new OrderParam();
            StringTool.setAllFields(I, data);
            return I;
        }


        //{
        //    #orderId#(0005)#orderId#
        //    #param#(参数)#param#
        //    #count#(12)#count#
        //}

        /// <summary>
        /// 将所有成员变量转化为字符串格式
        /// </summary>
        public string ToString()
        {
            return StringTool.getAllFields(this);
        }

        #endregion


        #region List数组与String互转

        public static string ToString(List<OrderParam> list)
        {
            StringBuilder sb = new StringBuilder();

            foreach(OrderParam param in list)
            {
                sb.AppendLine(param.ToString());
            }
            return sb.ToString();
        }

        public static List<OrderParam> ParseList(string data)
        {
            List<OrderParam> list = new List<OrderParam>();
            if (!data.Trim().Equals(""))
            {
                foreach (string iteam0 in data.Split('}'))
                {
                    string iteam = iteam0.Trim();
                    if (iteam.Equals("")) continue;
                    if (iteam.StartsWith("{")) iteam = iteam.Substring(1).Trim();

                    OrderParam param = OrderParam.Parse(iteam);
                    list.Add(param);
                }
            }
            return list;
        }

        #endregion


    }

}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace SciTools
{
    /// <summary>
    /// 读取Object对象的所有成员变量, 将类中所有变量信息转化为字符串进行存储
    /// </summary>
    public class StringTool
    {
        #region 成员变量序列化(转化为string、从string赋值)

        /// <summary>
        /// 获取Object对象,所有成员变量信息
        /// </summary>
        public static string getAllFields(Object obj)
        {
            string data = "\r\n";
            FieldInfo[] fields = obj.GetType().GetFields();
            foreach (FieldInfo field in fields)
            {
                string name = field.Name;                       // 类变量名称
                string value = field.GetValue(obj).ToString();  // 类变量值

                data += "\t" + NodeStr(value, name, false) + "\r\n";
            }
            data = "{" + data + "}";

            return data;
        }

        /// <summary>
        /// 设置Object对象的所有成员变量值(从data中解析数据)
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="data"></param>
        public static void setAllFields(Object obj, string data)
        {
            FieldInfo[] fields = obj.GetType().GetFields();
            foreach (FieldInfo field in fields)
            {
                string name = field.Name;
                string value = getNodeData(data, name, false);      // 获取变量字符串值

                Type type = field.FieldType;
                object valueObj = Convert.ChangeType(value, type);  // 转化为变量对应类型

                field.SetValue(obj, valueObj);                      // 设置值
            }
        }

        #endregion


        #region 节点数据生成、读取

        /// <summary>
        /// 从自定义格式的数据data中,获取nodeName对应的节点数据
        /// 
        /// NeedToRegister(false)NeedToRegister     // finalNode = false;
        /// RegisterPrice(1)                        // finalNode = true;
        /// </summary>
        /// <param name="data">待解析的数据</param>
        /// <param name="nodeName">节点名称</param>
        /// <param name="finalNode">是否为叶节点</param>
        /// <returns></returns>
        public static string getNodeData(string data, string nodeName, bool finalNode)
        {
            nodeName = "#" + nodeName + "#";
            if (!data.Contains(nodeName)) return "";

            try
            {
                string S = nodeName + "(", E = ")" + (finalNode ? "" : nodeName);
                int indexS = data.IndexOf(S) + S.Length;
                int indexE = data.IndexOf(E, indexS);

                return data.Substring(indexS, indexE - indexS);
            }
            catch (Exception) { return data; }
        }

        /// <summary>
        /// 将数据转化为节点形式
        /// </summary>
        public static string NodeStr(string data, string nodeName, bool finalNode)
        {
            nodeName = "#" + nodeName + "#";
            if (!finalNode) return nodeName + "(" + data + ")" + nodeName;
            else return nodeName + "(" + data + ")";
        }

        #endregion
    }

}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace SciTools
{
    /// <summary>
    /// 数据存储
    /// </summary>
    public class FileDB
    {
        static FileDB instance = null;
        public static FileDB Instance()
        {
            if (instance == null) instance = new FileDB(AppDomain.CurrentDomain.BaseDirectory + "DB.txt");
            return instance;
        }

        //----------------------

        string filePath = "";                   // 文件保存路径
        public List<OrderParam> list = null;    // 数据信息

        FileDB(string filePath)
        {
            this.filePath = filePath;

            string fileData = FileProcess.fileToString(filePath);
            list = OrderParam.ParseList(fileData);
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        public void Save()
        {
            string data = OrderParam.ToString(list);
            FileProcess.SaveProcess(data, filePath);
        }

        /// <summary>
        /// 清空数据
        /// </summary>
        public void Clear()
        {
            list.Clear();
            FileProcess.SaveProcess("", filePath);
        }

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SciTools
{
    public class FileProcess
    {
        #region 文件读取与保存

        /// <summary>
        /// 获取文件中的数据串
        /// </summary>
        public static string fileToString(String filePath)
        {
            string str = "";

            //获取文件内容
            if (System.IO.File.Exists(filePath))
            {
                bool defaultEncoding = filePath.EndsWith(".txt");

                System.IO.StreamReader file1;

                file1 = new System.IO.StreamReader(filePath);                  //读取文件中的数据
                //if (defaultEncoding) file1 = new System.IO.StreamReader(filePath, Encoding.Default);//读取文件中的数据
                //else file1 = new System.IO.StreamReader(filePath);                  //读取文件中的数据

                str = file1.ReadToEnd();                                            //读取文件中的全部数据

                file1.Close();
                file1.Dispose();
            }
            return str;
        }

        /// <summary>
        /// 保存数据data到文件处理过程,返回值为保存的文件名
        /// </summary>
        public static String SaveProcess(String data, String filePath, Encoding encoding = null)
        {
            //不存在该文件时先创建
            System.IO.StreamWriter file1 = null;
            if (encoding == null) file1 = new System.IO.StreamWriter(filePath, false);     //文件已覆盖方式添加内容
            else file1 = new System.IO.StreamWriter(filePath, false, encoding);            // 使用指定的格式进行保存

            file1.Write(data);                                                              //保存数据到文件

            file1.Close();                                                                  //关闭文件
            file1.Dispose();                                                                //释放对象

            return filePath;
        }

        /// <summary>
        /// 获取当前运行目录
        /// </summary>
        public static string CurDir()
        {
            return AppDomain.CurrentDomain.BaseDirectory;
        }

        #endregion
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值