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

Discord.NET SlashCommand如何将参数设为可空且非可选

在Discord.NET中实现可空但非可选的Slash命令参数

在Discord.NET里,默认string?这类可空引用类型会被判定为可选参数(用户可跳过填写),但你需要的是参数必须填写,却允许传入null/空值,可以用以下两种方式实现:

方法1:用MinLength(0)特性配合可空类型

给参数添加[MinLength(0)]特性,让Discord允许用户输入空字符串,同时保持参数必填状态,再用string?接收空值:

[SlashCommand("licenseaddaddress", "Adds an address to a license")]
public async Task ExecuteAsync(
    [Summary("LicenseKey", "The license key")]
    string licenseKey,
    [Summary("Address", "The address to be added")]
    string address,
    [Summary("Info", "Info that can be empty but must be provided")]
    [MinLength(0)] string? info)
{
    // 处理逻辑:info可能为null或空字符串
    if (string.IsNullOrEmpty(info))
    {
        // 空值处理逻辑
    }
    // 其他业务逻辑
}

方法2:自定义NotOptionalArgument特性

如果偏好通过自定义特性明确标识需求,可以自己实现特性配合参数解析:

  1. 定义自定义特性:
public class NotOptionalArgumentAttribute : ParameterPreconditionAttribute
{
    public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, IParameterInfo parameter, object value, IServiceProvider services)
    {
        // 确保参数必填(Discord Slash命令会强制用户填写),同时允许值为null
        return Task.FromResult(PreconditionResult.FromSuccess());
    }
}
  1. 在命令参数中使用:
[SlashCommand("licenseaddaddress", "Adds an address to a license")]
public async Task ExecuteAsync(
    [Summary("LicenseKey", "The license key")]
    string licenseKey,
    [Summary("Address", "The address to be added")]
    string address,
    [Summary("Info", "Info that can be null but must be provided")]
    [NotOptionalArgument] string? info)
{
    // 业务逻辑处理
}

重要提示

  • 别搞混「可选参数」和「可空参数」:可选参数是用户可以不填,你要的是用户必须填,但内容允许为空/ null。
  • Discord的Slash命令系统中,必填参数必须由用户提供输入,MinLength(0)是核心,它允许用户输入空字符串,配合可空类型就能实现需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 16:42:38