检查空参数的最佳方法(警卫条款) [英] Best way to check for null parameters (Guard Clauses)
问题描述
例如,您通常不希望构造函数中的参数为null,因此看到类似的东西是很正常的
For example, you usually don't want parameters in a constructor to be null, so it's very normal to see some thing like
if (someArg == null)
{
throw new ArgumentNullException(nameof(someArg));
}
if (otherArg == null)
{
throw new ArgumentNullException(nameof(otherArg));
}
它确实使代码有些混乱.
有什么方法可以比这更好地检查参数列表中的一个参数吗?
Is there any way to check an argument of a list of arguments better than this?
类似于检查所有参数,如果它们中的任何一个为空,并为您提供空的参数,则抛出ArgumentNullException.
Something like "check all of the arguments and throw an ArgumentNullException if any of them is null and that provides you with the arguments that were null.
顺便说一句,关于重复的问题声明,这不是关于用属性或内置标记来标记参数,而是所谓的保护子句",以确保对象接收初始化的依赖关系.
By the way, regarding duplicate question claims, this is not about marking arguments with attributes or something that is built-in, but what some call it Guard Clauses to guarantee that an object receives initialized dependencies.
推荐答案
使用较新版本的C#语言,您可以编写此代码而无需其他库或其他方法调用:
With newer version of C# language you can write this without additional library or additional method call:
_ = someArg ?? throw new ArgumentNullException(nameof(someArg));
_ = otherArg ?? throw new ArgumentNullException(nameof(otherArg));
这篇关于检查空参数的最佳方法(警卫条款)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!