如何在 C# 中使用构造函数将 JSON 对象反序列化为自身?

How to deserialize JSON object using constructor into itself in C#?

我想创建一个新对象,并在对象创建过程中进行 RPC 调用以获取其属性,然后 return 用这些属性填充对象。看这个例子:

using Newtonsoft.Json;

class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Person(int Id)
    {
        // here would be an RPC call to get the FirstName,LastName. result is JSON
        string result = "{\"Id\": 1, \"FirstName\": \"Bob\", \"LastName\": \"Jones\"}";
        this = JsonConvert.DeserializeObject<Person>(result);

    }
}
class Program
{
    static void Main(string[] args)
    {
        var p = new Person(1);
        // p.FirstName should be Bob
    }
}

我不知道如何在构造函数中执行此操作而不会出现 Whosebug 异常。

要考虑的一个选项是在 Person:

中使用静态方法
public static Person GetPerson(int Id)
{
    // here would be an RPC call to get the FirstName,LastName. result is JSON
    string result = "{\"Id\": 1, \"FirstName\": \"Bob\", \"LastName\": \"Jones\"}";
    return JsonConvert.DeserializeObject<Person>(result);

}

这避免了原始代码的递归性质。

另一种选择是将 class 更改为 structstructs 允许您分配给 this(不同于 classes)。他们有一个默认的构造函数(与你的接受参数的构造函数分开),所以没有递归行为。