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

前端 未结 2 486
有刺的猬
有刺的猬 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, 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(this) call being performed.

提交回复
热议问题