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

PactNet 4.5中如何在契约(IMatcher)里定义可空字段?

在PactNet 4.5中定义可选(可空)对象字段的消费者契约

要实现「字段可选择发送或不发送,发送则必须符合指定对象类型」的需求,你可以通过PactNet提供的Match.Nullable或Match.Optional结合Match.Type来配置,具体修改如下:

方案1:允许字段不存在、为null或符合结构

如果允许字段存在时为null,使用Match.Nullable包裹类型匹配规则:

Match.Type(new
{
    Id = Match.Type(123),
    Value = Match.Type(1.5),
    InternalProperty = Match.Nullable(Match.Type(new
    {
        Name = Match.Type("Test")
    })) // 该字段可选,发送时需符合结构,也可为null
})

方案2:仅允许字段不存在或符合结构(禁止为null)

如果要求字段存在时必须是非null的合法对象,使用Match.Optional:

Match.Type(new
{
    Id = Match.Type(123),
    Value = Match.Type(1.5),
    InternalProperty = Match.Optional(Match.Type(new
    {
        Name = Match.Type("Test")
    })) // 字段可选,存在时不能为null且需符合结构
})

核心区别

  • Match.Nullable():支持三种场景——字段不存在、字段存在且为null、字段存在且匹配结构
  • Match.Optional():仅支持两种场景——字段不存在、字段存在且匹配结构(不允许为null)

内容的提问来源于stack exchange,提问作者Felipe Ribeiro Montino

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 19:27:05