人们采用什么方法(如果有的话)管理班级中的防护条款爆炸?例如:
public void SomeMethod<T>(string var1, IEnumerable<T> items, int count)
{
if (string.IsNullOrEmpty(var1))
{
throw new ArgumentNullException("var1");
}
if (items == null)
{
throw new ArgumentNullException("items");
}
if (count < 1)
{
throw new ArgumentOutOfRangeException("count");
}
... etc ....
}
Run Code Online (Sandbox Code Playgroud)
在我目前正在进行的项目中,有许多类在公共方法上具有类似的一组保护条款.
我知道.NET 4.0代码合同,但目前这不是我们团队的选择.
例如,您通常不希望构造函数中的参数为null,因此看到类似的东西是很正常的
if (someArg == null)
{
throw new ArgumentNullException(nameof(someArg));
}
if (otherArg == null)
{
throw new ArgumentNullException(nameof(otherArg));
}
Run Code Online (Sandbox Code Playgroud)
它会使代码混乱.
有没有办法比这更好地检查一个参数列表的参数?
像"检查所有参数并抛出ArgumentNullException,如果它们中的任何一个为null并且为您提供null的参数"之类的东西.
顺便说一下,关于重复的问题声明,这不是关于用属性或内置的东西标记参数,而是有些人称之为Guard Clauses来保证对象接收初始化的依赖关系.
有没有办法找到导致控件从NullReferenceException流入catch块的对象名,这样我们就可以通过提供警报或记录null的对象来轻松调试?