This is because the serializer uses the type of the generic parameter, not the type of the passed value:public static string Serialize<TValue>(TValue value, JsonSerializerOptions options = null){ return WriteCoreString(value, typeof(TValue), options);}这会将typeof(IName)传递给WriteCoreString,并最终对该类型执行反射. This passes typeof(IName) to WriteCoreString, and on that type ultimately reflection is performed. 您可以通过明确地将类型传递给接受该类型的重载来解决此问题:You can work around this by explicitly passing the type to the overload that accepts that:var s3 = System.Text.Json.JsonSerializer.Serialize(p, p.GetType());这将返回:{"Name":"Waldo","Age":4}也可以使用object进行铸造,因为代码然后调用value.GetType() :Casting to object also works, as the code then calls value.GetType():var s4 = System.Text.Json.JsonSerializer.Serialize((object)p); 这篇关于当将specifc类强制转换为其他对象时,JsonSerializer的行为与预期的不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
11-02 02:39