Skip to main content
 首页 » 编程设计

c#之条件流中 out 参数的用法和 CA1002 fxcop 错误

2024年02月23日17dflying

我有一个 xml 解析代码,我在其中解析来自 xml 的多个节点和属性。使用短路,我可以避免 if 在我的代码中,因为我只想在肯定的情况下继续处理。但是我在使用时收到参数的 fxcop 错误 CA1002。

如何消除 fxcorp 错误?

public bool parseNode() 
{ 
    bool success = false; 
    string val1; 
    string val2; 
    string val3 
 
    success = TryGetAttributeValue(attribName1, out val1) && 
              TryGetAttributeValue(attribName2, out val2) && 
              TryGetAttributeValyue(attribName3, out val3); 
 
    if(success) 
    { 
        // do work 
    } 
} 
 
public bool TryGetAttributeValue(string attribName, out string value) 
{ 
} 

请您参考如下方法:

假设您正在谈论 CA1021 (避免使用参数)而不是 CA1002 (不要公开通用列表),FxCop 提示您的TryGetAttributeValue() 方法的out 参数。

您可以重构该方法,使其返回属性值而不是将其存储在 out 参数中,并在属性不存在时返回 null。从那里,您可以使用 null-coalescing operator ?? 保持相同的控制流:

public string TryGetAttributeValue(string attribName) 
{ 
    // Return attribute value, or null. 
} 
 
public bool ParseNode() 
{ 
    if ((TryGetAttributeValue(attribName1) 
        ?? TryGetAttributeValue(attribName2) 
        ?? TryGetAttributeValue(attribName3)) != null) { 
        // Do work. 
    } 
}