为什么不能JSON序列化的.Net静态或const成员变量?变量、静态、成员、序列化

2023-09-04 13:04:21 作者:当悲剧落幕后我在哪

我一直没能找到答案,这在任何地方,但是当我尝试序列化结构或类的静态或const成员变量,它们默认不序列化。如果我试图通过设置 MemberSerialization.OptIn 强制序列化,我得到一个错误。

I haven't been able to find the answer to this anywhere, but when I try to serialize a struct or class with static or const member variables, they don't serialize by default. If I try to force serialization by setting MemberSerialization.OptIn, I get an error.

恩。

[JsonObject(MemberSerialization.OptIn)]
public class Test
{    
    [JsonProperty]
    public int x = 1;

    [JsonProperty]
    public static int y = 2;
}

如果我尝试使用序列化这个类:

If I try to serialize this class with:

Test t = new Test();
string s = JsonConvert.SerializeObject( t );

我得到的错误错误获取从'Y''测试'值。同样的情况,如果y是常数。

I get the error Error getting value from 'y' on 'Test'. The same happens if y is const.

我的理论是静态和常量的值存储在某个地方特别在内存中,由于某种原因,JSON序列模试图访问它们。这完全是一种预感,虽然,我什么也看不到了的 C#参考静态这是任何帮助。我是比较新的C# - 这是一个真正的好奇心的问题比什么都重要,在这一点上

My theory is that static and const values are stored somewhere special in memory, and for some reason the Json serializer dies trying to access them. That's entirely a hunch though, and I see nothing in the C# Reference for Static that's of any help. I'm relatively new to C# - and this is really a curiosity question more than anything at this point.

推荐答案

如果它想它当然可以序列化静态变量。序列化是通过检查对象和类型与反射的API做的,这些API允许你做什么 - 没有任何技术原因,这些价值不能被序列化

It could certainly serialize the static variable if it wanted to. Serialization is done by inspecting objects and types with the Reflection APIs, and those APIs allow you to do "anything" -- there is no technical reason these values cannot be serialized.

有,然而,一个合乎逻辑的理由不默认情况下支持这一点:它并没有多大意义。您正在序列化的实例和静态常量成员的不是逻辑的一部分实例,但类作为一个整体的。

There is, however, a logical reason not to support this by default: it doesn't make much sense. You are serializing an instance, and static or const members are not logically part of an instance but of the class as a whole.

这是说,你仍然可以序列化静态成员,如果它是一个属性:

That said, you can still serialize static member if it's a property:

[JsonProperty]
public static int y { get; set; } // this will be serialized

当然,你完全可以通过创建一个自定义的覆盖序列化的行为 JsonConverter