2017-03-27 234 views
0

我有序列化問題。C#序列化:將類型爲Action的對象保存到文件

我的目錄樣子:

public List<Action> functions = new List<Action>(); 

後,我只需添加對象通過列出:

functions.Add(waypoint1); 

我的按鈕連載的樣子:

private async void metroButton8_Click(object sender, EventArgs e) // save wpts button 
     { 
      string dir = @"c:\temp"; 
      string serializationFile = Path.Combine(dir, "wpts.bin"); 
      //serialize 
      using (Stream stream = File.Open(serializationFile, FileMode.Create)) 
      { 
       var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 

       bformatter.Serialize(stream, functions); 
      } 

     } 


void Waypoint1() 
{ 
Console.WriteLine("Im first waypoint"); 
} 

當我嘗試只是保存到文件我有一個錯誤: 類型'System.Runtime.Serialization.SerializationExcep重刑'發生在mscorlib.dll中,但沒有在用戶代碼中處理

我應該在這裏添加什麼,只是不知道搜索了很多論壇,仍然不知道。請耐心等待c#中的新手。 謝謝!

+0

你能舉一個Waypoint1動作的例子嗎?它應該做什麼,以及爲什麼要序列化它? –

+0

@這不重要,這是做什麼,但我編輯我的主要給你。 – Michael

回答

0

並非所有的對象都可以被序列化。操作不可序列化。

你可以找到更多信息here或閱讀本answer

在某些情況下,你可以做一個簡單的方法。 而不是行動清單,你可以有MyAction列表。 其中MyAction是:

public class MyAction 
{ 
    //there could be several fields with data for Execute method. 
    //Type of this fields should be serializable. 
    public string DataForExecute { get; set; } 

    public void Execute() 
    { 
     //Do all you need here... 
    } 
} 

你可以甚至可以從該類繼承,有一個層次。但它使序列化/反序列化更復雜。

+0

所以我只需要創建一個可序列化的「東西」。我可以使用什麼,只是採取我現在在我的列表中一樣。 (方法對象的Luist) – Michael

+0

@Michael序列化解析並不是一件容易的事情。 [這裏](http://stackoverflow.com/a/1947932/4627031)LBushkin提出了一些一般的方法,並描述爲什麼它不適用於一般情況。 –

+0

好吧,我明白,但我可以使用其他方法來獲取方法對象的列表,而無需使用委託? – Michael

相關問題