You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请教System.Text.Json.JsonSerializer.Serialize的inputType参数用途

关于System.Text.Json.JsonSerializer.Serialize中inputType参数的疑问

System.Text.Json.JsonSerializer.Serialize是一组将C#对象序列化为JSON的重载方法。

非泛型重载均包含三个参数:

  • object? value:待序列化的对象
  • System.Text.Json.JsonSerializerOptions? options:用于配置序列化的各类选项
  • Type inputType:本次疑问的核心

官方仅将inputType描述为“待转换值的类型”,但该参数实际作用是什么?在此场景下,typeof(object)与value.GetType()是否存在实质性差异?

我查看了源码,发现这并非简单问题:该参数用于解析JsonTypeInfo,且typeof(object)在此处有特殊处理。

我进行了简易基准测试:

using System.Security.Cryptography;
using System.Text.Json;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

BenchmarkRunner.Run<JsonBench>();

sealed record Bla(string Foo, int Bar);

public class JsonBench
{
    readonly Bla value = new Bla("a", 2);
    
    [Benchmark]
    public string WithGenerics() => JsonSerializer.Serialize(value);

    [Benchmark]
    public string WithGetType() => JsonSerializer.Serialize(value, value.GetType());

    [Benchmark]
    public string WithObjectType() => JsonSerializer.Serialize(value, typeof(object));

    readonly Type cachedObject = typeof(object), cachedBla = typeof(Bla);

    [Benchmark]
    public string WithCachedGetType() => JsonSerializer.Serialize(value, cachedBla);
    
    [Benchmark]
    public string WithCachedObjectType() => JsonSerializer.Serialize(value, cachedObject);
}

测试显示,对于小型对象,使用typeof(object)会产生约10ns的微小性能开销。仅此而已吗?是否存在开销更大的极端场景?若value.GetType()始终更快,为何要设置该参数?

简言之:我尚未明确Type inputType参数的实际用途,恳请各位予以解惑。


内容的提问来源于stack exchange,提问作者Eamon Nerbonne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 19:10:19