C# 序列化c对象公共方法

C# 序列化c对象公共方法,c#,json,C#,Json,我有一个C类和一个公共方法,如下所示。我想使用Newtownsoft在JSON中序列化这个类。问题是Json序列化只能序列化公共属性和字段。如何序列化方法 public class Employee { public void ExecuteSomeOperation() { //code... } } 无法将C方法序列化为JSON对象表示。您希望序

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

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

无法将C方法序列化为JSON对象表示。

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

这是一个二进制序列化。你不能像你自己说过的那样使用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();
反序列化样本

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();

JSON仅用于数据,不是可执行代码。OP表示他们希望序列化为JSON,这是文本序列化,不是二进制序列化,因此无法表示可执行代码。我不认为他对序列化缺乏理解。所以我们只剩下一件事了——猜猜他问了些什么:嗯。。如果代码足够好,允许反编译,请参阅此讨论。。。然后,在提取反编译代码后,将其添加到json数据中。。。