相关疑难解决方法(0)

重构保护条款

人们采用什么方法(如果有的话)管理班级中的防护条款爆炸?例如:

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代码合同,但目前这不是我们团队的选择.

c# validation guard-clause

29
推荐指数
1
解决办法
1万
查看次数

检查空参数的最佳方法(Guard子句)

例如,您通常不希望构造函数中的参数为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来保证对象接收初始化的依赖关系.

c# constructor arguments

20
推荐指数
8
解决办法
2万
查看次数

有没有办法找出导致NullReferenceException的对象?

有没有办法找到导致控件从NullReferenceException流入catch块的对象名,这样我们就可以通过提供警报或记录null的对象来轻松调试?

c# asp.net

6
推荐指数
1
解决办法
1313
查看次数

标签 统计

c# ×3

arguments ×1

asp.net ×1

constructor ×1

guard-clause ×1

validation ×1