简体   繁体   中英

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.

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. I've read where it's bad practice for the BaseClass to know anything about the derived class. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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