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

C#中是否有类似字符串Guard的整数参数校验方法?

解决方案

1. 使用CommunityToolkit.Diagnostics内置方法

CommunityToolkit.Diagnostics的Guard类本身就提供了针对数值类型的非零校验方法Guard.IsNotZero,一行代码就能完成校验并自动抛出异常,完全替代你原来的三行if判断:

Guard.IsNotNullOrEmpty(myname);
Guard.IsNotNullOrEmpty(yourname);
Guard.IsNotZero(myage, nameof(myage), "Your age cannot be 0");

如果不需要自定义错误消息,也可以简化为:

Guard.IsNotZero(myage, nameof(myage));

此时会抛出默认的ArgumentException,提示"Value cannot be zero."。

2. 自定义扩展方法(适配旧版本或特殊需求)

如果你的CommunityToolkit.Diagnostics版本较低,没有内置IsNotZero方法,可以自己给Guard类写扩展方法,实现复用:

using CommunityToolkit.Diagnostics;
using System;

public static class GuardExtensions
{
    public static void IsNotZero(this Guard _, int value, string parameterName, string? errorMessage = null)
    {
        if (value == 0)
        {
            throw new ArgumentException(errorMessage ?? "参数不能为0", parameterName);
        }
    }
}

使用方式和内置方法一致:

Guard.IsNotZero(myage, nameof(myage), "Your age cannot be 0");

内容的提问来源于stack exchange,提问作者José Mauro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:25:36