【问题标题】:serialize c# object public method序列化 c# 对象公共方法
【发布时间】:2015-11-19 11:46:38
【问题描述】:

我有一个带有公共方法的 C# 类,如下所示。我想使用 Newtownsoft 在 JSON 中序列化这个类。问题是 Json 序列化只序列化公共属性和字段。如何让方法序列化?

     public class Employee
        {
            public void ExecuteSomeOperation()
            {
                //code...
            }
        }

【问题讨论】:

  • JSON 仅用于数据,不能用于可执行代码。

标签: c# json


【解决方案1】:

您不能将 C# 方法序列化为 JSON 对象表示。

【讨论】:

    【解决方案2】:

    您希望序列化什么? “代码”通常不会序列化。但是,可能您的意思是序列化函数的“输出”。这可能包含属性或变量,因此创建属性或变量并从此方法设置它们;属性/变量将被序列化。

    【讨论】:

    【解决方案3】:

    这是一个二进制序列化。不能像你自己说的那样使用json。

    我相信您会根据您的情况调整下一个代码示例:

    序列化样本

    Stream stream = File.Open("EmployeeInfo.osl", FileMode.Create);
    BinaryFormatter bformatter = new BinaryFormatter();
    
    Console.WriteLine("Writing Employee Information");
    bformatter.Serialize(stream, mp);
    stream.Close();
    

    反序列化样本

    //Open the file written above and read values from it.
    stream = File.Open("EmployeeInfo.osl", FileMode.Open);
    bformatter = new BinaryFormatter();
    
    Console.WriteLine("Reading Employee Information");
    mp = (Employee)bformatter.Deserialize(stream);
    stream.Close();
    

    【讨论】:

    • OP 声明他们要序列化为 JSON,这是文本的,不是二进制序列化的,因此无法表示可执行代码。
    • 我不认为他对序列化缺乏了解。所以我们只剩下一件事了——猜猜他问的是什么:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 2016-03-04
    相关资源
    最近更新 更多