2017-08-30 95 views
0

我有这个类C#自定义序列化和反序列化的简单类

class MyClass{ 
    int x; 
    byte[] arr; 
} 

我想序列化的文本文件,但在自定义的方式。

我希望在写我想写的x值之前:x值是:x。

并对arr进行一些操作(如每个值的+1)并移动标签。

,然后“价值又是” X的值有“美好的一天”与标签

我如何可以序列像这样的txt文件,

以及如何从txt文件反序列化像那样的MyClass?

例如:X = 4,ARR = {1,2,3} txt文件将是

the value of X is: 4 
    arr is: 2,3,4 
    the value again is:5 have a nice day 

我怎样才能做到这一点,请? 我不想为那个var做特殊的获取属性,因为在我的程序中我使用这个Get。

回答

1

序列化是比你正在尝试做不同的,但如果你想特殊的格式化输出,有些人会做的ToString()方法的重写,但你可以创建另一个方法类似...

public string textOutput() 
    { 
     var sb = new StringBuilder(); 
     sb.AppendFormat("the value of X is: {0}\r\n arr is: ", x); 
     for (var i = 0; i < arr.Length; i++) 
      sb.AppendFormat("{0}{1}", i == 0 ? "" : ", ", arr[i]); 

     // don't know where your 5 value is coming from though... but place-holdered it 
     sb.AppendFormat("\r\n  the value again is: {0} have a nice day", 5); 

     return sb.ToString(); 
    } 

并根据需要编写输出。或者你可以创建它作为它自己的getter属性,也是如此。

相关问题