考虑这段代码:
private static void Main(string[] args)
{
var person = new Person { Manager = new Manager { Name = "Shahrooz" }, Name = "Sina" };
Console.WriteLine("I am {0} my manager is {1}", person.Name, person.Manager.Name);
//Outpu:I am Sina my manager is Shahrooz
var newManager = person.Manager;
person.Manager = null;
new Thread(() => File.WriteAllText( Path.Combine("C:\\", string.Format("{0}.txt", person.Name)), new JavaScriptSerializer().Serialize(person))).Start();
Console.WriteLine("I am {0} my manager is", person.Name);
person.Manager = newManager;
Console.ReadLine();
}
}
public class Person
{
public string Name { get; set; }
public Manager Manager { get; set; }
}
public class Manager
{
public string Name { get; set; }
}
我正在尝试使用JavaScriptSerializer
. 在序列化之前,我将 person's manager 设置为 null 但我在文本文件中得到了很好的结果:
{"姓名":"新浪","经理":{"姓名":"Shahrooz"}}
我混淆了。请帮我。
更新:
我更改了我的代码。没关系:
internal class Program
{
private static void Main(string[] args)
{
var person = new Person { Manager = new Manager { Name = "Shahrooz" }, Name = "Sina" };
Console.WriteLine("I am {0} my manager is {1}", person.Name, person.Manager.Name);
//Outpu:I am Sina my manager is Shahrooz
var x = person.Manager;
person.Manager = null;
add(person);
Console.WriteLine("I am {0} my manager is", person.Name);
person.Manager = x;
Console.ReadLine();
}
public static async void add(Person person)
{
await AddToFile(person);
}
private async static Task AddToFile(Person person)
{
File.WriteAllText(Path.Combine("C:\\", string.Format("{0}.txt", person.Name)), new JavaScriptSerializer().Serialize(person));
}
}
public class Person
{
public string Name { get; set; }
public Manager Manager { get; set; }
}
public class Manager
{
public string Name { get; set; }
}