Override ToString() is not working in abstract class (.net-core 3.1)

前端 未结 2 483
有刺的猬
有刺的猬 2021-01-23 06:02

When interpolating objects into strings (mainly for logging purposes), it needs to be explicitly serialized otherwise what you get is:

.

        
相关标签:
2条回答
  • 2021-01-23 06:13

    Change your serialization code to (assuming you are using System.Text.Json):

    public abstract class BaseModel
    {
        public override string ToString()
        {
            return JsonSerializer.Serialize(this, this.GetType());
        }
    }
    

    You are using generic JsonSerializer.Serialize<TValue>(TValue, JsonSerializerOptions) overload in your base class so during compilation generic parameter TValue is subsitued with your BaseModel class, which has no properties, basically ending in JsonSerializer.Serialize<BaseModel>(this) call being performed.

    0 讨论(0)
  • 2021-01-23 06:27

    The .NET Core json serializer method you used is generic, like this:

    public static string Serialize<TValue> (TValue value,
        System.Text.Json.JsonSerializerOptions options = default);
    

    By design, it only considers the properties in TValue when it serializes, and since you called it from your abstract class, with this, which of course will then be of the abstract class type, it only considers properties in the abstract class.

    Basically your call is inferred to be

    return JsonSerializer.Serialize<BaseModel>(this);
    

    Fortunately, it is easy to fix, simply switch to calling the non-generic method:

    return JsonSerializer.Serialize(this, GetType());
    

    Now it uses runtime information about which type you're actually calling it about instead of the abstract class, and should correctly serialize properties from your descendant type.

    0 讨论(0)
提交回复
热议问题