在C#中对只读属性进行奇怪的Json反序列化

xyhw6mcr  于 2023-08-08  发布在  C#
关注(0)|答案(1)|浏览(139)

有人能解释一下它是怎么工作的吗?我甚至使用反射来设置B值,但它说B没有设置值。Newtonsoft.Json如何实现这一点?

public class A
{
    private int a = 10;
    public int B => a;
}

var a = new A();
var json = JsonConvert.SerializeObject(a);//json={"B":10}

//my expectation: this will have error, because B only have getter, dont have setter
//in reality: this run OK, and aa.B = aa.a = 10
var aa = JsonConvert.DeserializeObject<A>(json);

字符串

6ioyuze2

6ioyuze21#

它实际上并没有反序列化B属性。它之所以“工作”,是因为默认情况下是a == 10。以下面的代码为例:

public class A
{
    private int a = 10;
    public int B => a;

    public A(){}

    public A(int a)
    {
        this.a = a;
    }
}

var a = new A(5);
var json = JsonConvert.SerializeObject(a); //json={"B":5}
var aa = JsonConvert.DeserializeObject<A>(json);
Console.WriteLine(aa.B); // Prints 10.

字符串

相关问题