C# 序列化:将带有 Action 类型对象的 List 保存到文件

C# Serialization: save List with objects of type Action to file

我有序列化问题。

我的列表如下:

 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.SerializationException' 类型的异常发生在 mscorlib.dll 但未在用户代码中处理

我应该在这里添加什么不知道搜索了很多论坛仍然不知道。请 c# 新手耐心等待。 谢谢!

并非所有对象都可以序列化。动作不可序列化。

您可以找到更多信息here or read this 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...
    }
}

您甚至可以继承此 class 并拥有层次结构。但它使 serialization/deserialization 更复杂。