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

如何检测C#方法参数是否为可空类型(含string?)

检测方法参数的可空类型(含引用类型可空)

问题背景

值类型可空(如int?)可通过Nullable.GetUnderlyingType(p.ParameterType) != null检测,但引用类型可空(如string?)是编译时nullable注解,运行时参数类型仍为string,常规类型检测无法识别,需通过注解属性判断。

解决方案

单个参数可空检测

通过结合值类型可空判断与NullableAttribute读取,实现完整检测:

using System.Reflection;
using System.Runtime.CompilerServices;

public static bool IsParameterNullable(ParameterInfo parameter)
{
    // 检测值类型可空(如int?)
    if (Nullable.GetUnderlyingType(parameter.ParameterType) != null)
    {
        return true;
    }

    // 读取引用类型的可空注解属性
    var nullableAttr = parameter.GetCustomAttribute<NullableAttribute>();
    if (nullableAttr != null)
    {
        // Argument数组中1表示可空,0表示不可空
        return nullableAttr.Argument.Length > 0 && nullableAttr.Argument[0] == 1;
    }

    // 未标注nullable注解的引用类型,默认视为不可空(需项目启用nullable上下文)
    return false;
}

批量检测方法所有参数

public static bool AllParametersAreNullable(MethodInfo method)
{
    return method.GetParameters().All(IsParameterNullable);
}

关键说明

  • 引用类型可空的检测依赖项目启用nullable上下文(项目文件中设置<Nullable>enable</Nullable>),否则编译时不会生成NullableAttribute。
  • string?这类注解在编译后会为参数附加NullableAttribute,通过读取该属性的Argument值即可判断可空状态。

示例验证

针对目标方法:

public async Task<IActionResult> HierarchyOfRanking(string? orderByType)
{
}

调用IsParameterNullable检测orderByType参数,会返回true。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 05:25:18