构造函数不要求反序列化 [英] Constructors Not Called On Deserialization

查看:129
本文介绍了构造函数不要求反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过的许多地方都指出,在反序列化方面,.NET Framework调用了 FormatterServices.GetUninitializedObject ,其中未调用构造函数且未设置字段初始值设定项。如果是这样,为什么要调用我的构造函数?

Various places I've been reading have pointed out that on deserialization, the .NET Framework makes a call to FormatterServices.GetUninitializedObject, in which constructors are not called and field initializers are not set. If this is true, why is my constructor being called? Are there instances where constructors and field initializers could be called?

我的课:

[DataContract]
public class TestClass
{
    [DataMember]
    public string Val1 { get; set; }

    [DataMember]
    public string Val2 { get; set; }

    [DataMember]
    public bool NonDefaultBool = true;

    private int _nonDefaultInt = 1234;

    [DataMember]
    public int NonDefaultInt
    {
        get { return _nonDefaultInt; }
        set { _nonDefaultInt = value; }
    }

    public TestClass()
    {
        Val1 = "hello";
    }
}

我的反序列化代码:

var json2 =
@"{
    ""Val1"":""hello""
}";

using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json2)))
{
    var thing = DeserializeJsonObject<TestClass>(ms);
    Console.WriteLine(GetSerializedData(thing));
}

// ... code left out

protected static TModel DeserializeJsonObject<TModel>(Stream data) where TModel : class
{
    DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(TModel));
    return jsonSerializer.ReadObject(data) as TModel;
}

static string GetSerializedData<T>(T data)
{
    DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T), _knownTypes);

    using (MemoryStream ms = new MemoryStream())
    {
        jsonSerializer.WriteObject(ms, data);
        return Encoding.UTF8.GetString(ms.ToArray());
    }
}

我的输出(格式化并评论了我):

My output (formatted and commented me):

{
    "NonDefaultBool":false, // field initializer not set
    "NonDefaultInt":0, // field initializer not set
    "Val1":"hello", // constructor called
    "Val2":null
}


推荐答案

您正在反序列化json2字符串。

You're deserializing the json2 string.

var json2 =

@ {

Val1:你好

};

我不相信正在调用构造函数,但是JSON字符串分配了 hello。

I don't believe the constructor is being called, but the 'hello' is being assigned by the JSON string.

这篇关于构造函数不要求反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆