2017-08-30 175 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屬性,也是如此。