加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 处理方法参数的null属性的最佳方法

发布时间:2020-12-15 08:47:15 所属栏目:百科 来源:网络整理
导读:检查方法的参数时,如果它为null,则抛出ArgumentNullException.请参阅以下方法中的第一行.但是参数上的属性应该不为null呢?如果我尝试以相同的方式处理它们,我会收到代码分析错误: CA2208 Instantiate argument exceptions correctly Method ‘PriorityDera
检查方法的参数时,如果它为null,则抛出ArgumentNullException.请参阅以下方法中的第一行.但是参数上的属性应该不为null呢?如果我尝试以相同的方式处理它们,我会收到代码分析错误:

CA2208 Instantiate argument exceptions correctly Method
‘PriorityDeratingComponentLogic.CreateItem(IvSimulation)’ passes
‘ivSimulation.SolarPanel’ as the ‘paramName’ argument to a
‘ArgumentNullException’ constructor. Replace this argument with one of
the method’s parameter names. Note that the provided parameter name
should have the exact casing as declared on the method.

public DeratingComponentBase CreateItem(IvSimulation ivSimulation)
{
    if (ivSimulation == null) { throw new ArgumentNullException("ivSimulation"); }
    if (ivSimulation.SolarPanel == null) { throw new ArgumentNullException("ivSimulation.SolarPanel"); }
    if (ivSimulation.GlobalEquipment == null) { throw new ArgumentNullException("ivSimulation.GlobalEquipment"); }

    // ... method body here
}

CA错误是我应该抑制的,还是有一种普遍接受的方式来更好地处理这个问题?也许问题是上游问题,我们甚至不应该检查这些属性是否为空?

解决方法

抛出ArgumentNullException旨在指示参数本身为null.但是,当其中一个参数组件为null,但参数本身不为null时,正确的异常是ArgumentException,参数名称为参数:
if (ivSimulation.GlobalEquipment == null) {
    throw new ArgumentException("GlobalEquipment cannot be null","ivSimulation");
 }

这提供了有关消息中错误的信息,同时将ivSimulation指定为参数名称.

注意:我假设您无法在IvSimulation的构造函数中验证GlobalEquipment,因为抛出ArgumentNullException将是该构造函数中完全有效的选择.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读