当前位置:   article > 正文

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

c# object存储数据

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

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

获取变量名称:

string name = field.Name;

 获取变量值:

Object valueObj = field.GetValue(obj);

设置obj中指定变量的值:

  1. string value = "123";
  2. Type type = field.FieldType;
  3. object valueObj = Convert.ChangeType(value, type); // 转化为变量对应类型
  4. field.SetValue(obj, valueObj); // 设置值

类对象数据存储示例:


 源码:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. namespace SciTools
  7. {
  8. public class OrderParam
  9. {
  10. public string orderId = "";
  11. public string param = "";
  12. public int count = 0;
  13. #region 类对象逻辑
  14. public OrderParam(string orderId = "", string param = "", int count = 0)
  15. {
  16. this.orderId = orderId;
  17. this.param = param;
  18. this.count = count;
  19. }
  20. /// <summary>
  21. /// 从data数据构建OrderParam
  22. /// </summary>
  23. public static OrderParam Parse(string data)
  24. {
  25. OrderParam I = new OrderParam();
  26. StringTool.setAllFields(I, data);
  27. return I;
  28. }
  29. //{
  30. // #orderId#(0005)#orderId#
  31. // #param#(参数)#param#
  32. // #count#(12)#count#
  33. //}
  34. /// <summary>
  35. /// 将所有成员变量转化为字符串格式
  36. /// </summary>
  37. public string ToString()
  38. {
  39. return StringTool.getAllFields(this);
  40. }
  41. #endregion
  42. #region List数组与String互转
  43. public static string ToString(List<OrderParam> list)
  44. {
  45. StringBuilder sb = new StringBuilder();
  46. foreach(OrderParam param in list)
  47. {
  48. sb.AppendLine(param.ToString());
  49. }
  50. return sb.ToString();
  51. }
  52. public static List<OrderParam> ParseList(string data)
  53. {
  54. List<OrderParam> list = new List<OrderParam>();
  55. if (!data.Trim().Equals(""))
  56. {
  57. foreach (string iteam0 in data.Split('}'))
  58. {
  59. string iteam = iteam0.Trim();
  60. if (iteam.Equals("")) continue;
  61. if (iteam.StartsWith("{")) iteam = iteam.Substring(1).Trim();
  62. OrderParam param = OrderParam.Parse(iteam);
  63. list.Add(param);
  64. }
  65. }
  66. return list;
  67. }
  68. #endregion
  69. }
  70. }
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. namespace SciTools
  7. {
  8. /// <summary>
  9. /// 读取Object对象的所有成员变量, 将类中所有变量信息转化为字符串进行存储
  10. /// </summary>
  11. public class StringTool
  12. {
  13. #region 成员变量序列化(转化为string、从string赋值)
  14. /// <summary>
  15. /// 获取Object对象,所有成员变量信息
  16. /// </summary>
  17. public static string getAllFields(Object obj)
  18. {
  19. string data = "\r\n";
  20. FieldInfo[] fields = obj.GetType().GetFields();
  21. foreach (FieldInfo field in fields)
  22. {
  23. string name = field.Name; // 类变量名称
  24. string value = field.GetValue(obj).ToString(); // 类变量值
  25. data += "\t" + NodeStr(value, name, false) + "\r\n";
  26. }
  27. data = "{" + data + "}";
  28. return data;
  29. }
  30. /// <summary>
  31. /// 设置Object对象的所有成员变量值(从data中解析数据)
  32. /// </summary>
  33. /// <param name="obj"></param>
  34. /// <param name="data"></param>
  35. public static void setAllFields(Object obj, string data)
  36. {
  37. FieldInfo[] fields = obj.GetType().GetFields();
  38. foreach (FieldInfo field in fields)
  39. {
  40. string name = field.Name;
  41. string value = getNodeData(data, name, false); // 获取变量字符串值
  42. Type type = field.FieldType;
  43. object valueObj = Convert.ChangeType(value, type); // 转化为变量对应类型
  44. field.SetValue(obj, valueObj); // 设置值
  45. }
  46. }
  47. #endregion
  48. #region 节点数据生成、读取
  49. /// <summary>
  50. /// 从自定义格式的数据data中,获取nodeName对应的节点数据
  51. ///
  52. /// NeedToRegister(false)NeedToRegister // finalNode = false;
  53. /// RegisterPrice(1) // finalNode = true;
  54. /// </summary>
  55. /// <param name="data">待解析的数据</param>
  56. /// <param name="nodeName">节点名称</param>
  57. /// <param name="finalNode">是否为叶节点</param>
  58. /// <returns></returns>
  59. public static string getNodeData(string data, string nodeName, bool finalNode)
  60. {
  61. nodeName = "#" + nodeName + "#";
  62. if (!data.Contains(nodeName)) return "";
  63. try
  64. {
  65. string S = nodeName + "(", E = ")" + (finalNode ? "" : nodeName);
  66. int indexS = data.IndexOf(S) + S.Length;
  67. int indexE = data.IndexOf(E, indexS);
  68. return data.Substring(indexS, indexE - indexS);
  69. }
  70. catch (Exception) { return data; }
  71. }
  72. /// <summary>
  73. /// 将数据转化为节点形式
  74. /// </summary>
  75. public static string NodeStr(string data, string nodeName, bool finalNode)
  76. {
  77. nodeName = "#" + nodeName + "#";
  78. if (!finalNode) return nodeName + "(" + data + ")" + nodeName;
  79. else return nodeName + "(" + data + ")";
  80. }
  81. #endregion
  82. }
  83. }
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. namespace SciTools
  7. {
  8. /// <summary>
  9. /// 数据存储
  10. /// </summary>
  11. public class FileDB
  12. {
  13. static FileDB instance = null;
  14. public static FileDB Instance()
  15. {
  16. if (instance == null) instance = new FileDB(AppDomain.CurrentDomain.BaseDirectory + "DB.txt");
  17. return instance;
  18. }
  19. //----------------------
  20. string filePath = ""; // 文件保存路径
  21. public List<OrderParam> list = null; // 数据信息
  22. FileDB(string filePath)
  23. {
  24. this.filePath = filePath;
  25. string fileData = FileProcess.fileToString(filePath);
  26. list = OrderParam.ParseList(fileData);
  27. }
  28. /// <summary>
  29. /// 保存数据
  30. /// </summary>
  31. public void Save()
  32. {
  33. string data = OrderParam.ToString(list);
  34. FileProcess.SaveProcess(data, filePath);
  35. }
  36. /// <summary>
  37. /// 清空数据
  38. /// </summary>
  39. public void Clear()
  40. {
  41. list.Clear();
  42. FileProcess.SaveProcess("", filePath);
  43. }
  44. }
  45. }
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace SciTools
  6. {
  7. public class FileProcess
  8. {
  9. #region 文件读取与保存
  10. /// <summary>
  11. /// 获取文件中的数据串
  12. /// </summary>
  13. public static string fileToString(String filePath)
  14. {
  15. string str = "";
  16. //获取文件内容
  17. if (System.IO.File.Exists(filePath))
  18. {
  19. bool defaultEncoding = filePath.EndsWith(".txt");
  20. System.IO.StreamReader file1;
  21. file1 = new System.IO.StreamReader(filePath); //读取文件中的数据
  22. //if (defaultEncoding) file1 = new System.IO.StreamReader(filePath, Encoding.Default);//读取文件中的数据
  23. //else file1 = new System.IO.StreamReader(filePath); //读取文件中的数据
  24. str = file1.ReadToEnd(); //读取文件中的全部数据
  25. file1.Close();
  26. file1.Dispose();
  27. }
  28. return str;
  29. }
  30. /// <summary>
  31. /// 保存数据data到文件处理过程,返回值为保存的文件名
  32. /// </summary>
  33. public static String SaveProcess(String data, String filePath, Encoding encoding = null)
  34. {
  35. //不存在该文件时先创建
  36. System.IO.StreamWriter file1 = null;
  37. if (encoding == null) file1 = new System.IO.StreamWriter(filePath, false); //文件已覆盖方式添加内容
  38. else file1 = new System.IO.StreamWriter(filePath, false, encoding); // 使用指定的格式进行保存
  39. file1.Write(data); //保存数据到文件
  40. file1.Close(); //关闭文件
  41. file1.Dispose(); //释放对象
  42. return filePath;
  43. }
  44. /// <summary>
  45. /// 获取当前运行目录
  46. /// </summary>
  47. public static string CurDir()
  48. {
  49. return AppDomain.CurrentDomain.BaseDirectory;
  50. }
  51. #endregion
  52. }
  53. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/111845
推荐阅读
相关标签
  

闽ICP备14008679号