c# - 在方法中混合 params 和 nameof 来检查空值

标签 c# c#-6.0

我创建了一个方法,旨在检查空值并使用正确的参数名称抛出 NullArgumentException

方法是这样的:

public static void CheckNotNull(params object[] args)
{
     // if any of the args is null
     // then Throw new ArgumentNullException(nameof(…))
}

我什至不确定这是否可能!是吗?

最佳答案

此方法中唯一的参数是 args,您可以使用 nameof 检查它:

public static void CheckNotNull(params object[] args)
{
    if (args == null)
    {
        throw new ArgumentNullException(nameof(args))
    }
}

这些项本身也可以为null,但它们并不是真正的参数,而且它们是无名的。您也可以检查它们并抛出适当的异常:

if (args.Any(item => item == null))
{
    throw new ArgumentException($"{nameof(args)} cannot contain nulls");
}

关于c# - 在方法中混合 params 和 nameof 来检查空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28532429/

相关文章:

c# - 保持 Service Fabric Actor 的状态

c# - 从派生类调用的虚拟方法中的 typeof this

C# 使用对象按值排序列表

c# - 根据 ViewModel 的属性更改 div 类

c# - string interpolation 和 string.format 哪个性能更好?

c# - Roslyn 和 .NET 运行时版本

c# - 为什么这在 C# 中不合法?

visual-studio-2015 - TFS 2013 Build 强制 MSBuild 使用 Visual Studio 2015

c# - 使用空条件 bool ?在 if 语句中

c# - Roslyn 中的代理缓存行为更改