使用 DataContractSerializer 时设置属性的初始值

发布于 2024-08-30 11:58:34 字数 736 浏览 5 评论 0原文

如果我使用 DataContractSerializer 序列化并稍后反序列化一个类,如何控制未序列化的属性的初始值?

考虑下面的 Person 类。其数据协定设置为序列化 FirstNameLastName 属性,但不序列化 IsNew 属性。我希望 IsNew 初始化为 TRUE,无论新 Person 是被实例化为新实例还是从文件反序列化。

通过构造函数很容易做到这一点,但据我了解,DataContractSerializer 不会调用构造函数,因为它们可能需要参数。

[DataContract(Name="Person")]
public class Person 
{
    [DataMember(Name="FirstName")]
    public string FirstName { get; set; }

    [DataMember(Name = "LastName")]
    public string LastName { get; set; }

    public bool IsNew { get; set; }

    public Person(string first, string last)
    {
        this.FirstName = first;
        this.LastName = last;
        this.IsNew = true;
    }
}

If I am serializing and later deserializing a class using DataContractSerializer how can I control the initial values of properties that were not serialized?

Consider the Person class below. Its data contract is set to serialize the FirstName and LastName properties but not the IsNew property. I want IsNew to initialize to TRUE whether a new Person is being instantiate as a new instance or being deserialized from a file.

This is easy to do through the constructor, but as I understand it DataContractSerializer does not call the constructor as they could require parameters.

[DataContract(Name="Person")]
public class Person 
{
    [DataMember(Name="FirstName")]
    public string FirstName { get; set; }

    [DataMember(Name = "LastName")]
    public string LastName { get; set; }

    public bool IsNew { get; set; }

    public Person(string first, string last)
    {
        this.FirstName = first;
        this.LastName = last;
        this.IsNew = true;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

死开点丶别碍眼 2024-09-06 11:58:34

实际上,正确的方法是使用 OnDeserializing 属性(注意“ing”后缀)。在反序列化成员值之前调用标有此属性的方法。

Actually the correct way of doing it is by using the OnDeserializing attribute (notice the "ing" suffix). The method marked with this attribute is called before the member values are deserialized.

她比我温柔 2024-09-06 11:58:34

您可以使用序列化回调。将以下方法添加到您的 Person 类中:

[OnDeserialized]
void OnDeserialized(StreamingContext context)
{
    this.IsNew = true;
}

另一种选择是删除 [DataContract] 和 [DataMember] 属性。在这种情况下,DCSerializer 将在反序列化时调用您的构造函数。

You can use a serialization callback. Add the following method to your Person class:

[OnDeserialized]
void OnDeserialized(StreamingContext context)
{
    this.IsNew = true;
}

Another option is to remove the [DataContract] and [DataMember] attributes. In this case DCSerializer will call your constructor when it deserializes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文