Reputation: 3266
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?
Upvotes: 0
Views: 79
Reputation: 88996
This will work with the following code:
public class BaseClass
{
[JsonIgnore]
public string Payload => JsonSerializer.Serialize(this, this.GetType());
}
See the explanation here.
Upvotes: 1