简体   繁体   English

具有序列化派生类能力的基类

[英]Base Class with Ability to Serialize Derived Class

I want to create a base class that contains a property that serializes the current instance of the class.我想创建一个基类,其中包含一个序列化类的当前实例的属性。 That way I don't have to add the Payload property to every class that I want to serialize, and if I wanted to change the way I serialize, I wouldn't have to change it in ALL my classes.这样我就不必将Payload属性添加到我想序列化的每个类中,如果我想改变我的序列化方式,我就不必在我的所有类中都改变它。

public class BaseClass
{
    public string Payload => JsonSerializer.Serialize(this);
}


public class DerivedClass : BaseClass
{
    public string ClientId { get; set; }

    ...other properties left out
}

The problem is that this is always in the context of the BaseClass , so it knows nothing about the derived class.问题是this总是在BaseClass的上下文中,所以它对派生类一无所知。 I've read where it's bad practice for the BaseClass to know anything about the derived class.我已经阅读了BaseClass了解派生类的任何不良做法的地方。 So in this scenario, what are my options?那么在这种情况下,我的选择是什么?

This will work with the following code:这将适用于以下代码:

public class BaseClass
{
    [JsonIgnore]
    public string Payload => JsonSerializer.Serialize(this, this.GetType());
}

See the explanation here .请参阅此处的说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM