我可以安全地忽略 CodeAnalysis 警告:替换字符串 == ""与 string.IsNullOrEmpty?

发布于 2024-08-09 21:20:52 字数 602 浏览 10 评论 0 原文

我有与此类似的代码:

string s = CreateString();
if (s == "") foo(s);

如果 s 等于“”,则应调用 foo。如果 string 为 null(这种情况永远不会发生),那么 NullReferenceException 就可以了(因为这毕竟是一种例外情况)。

CodeAnalysis 告诉我测试 s.IsNullOrEmpty。这会以意想不到的方式改变功能。

性能不是问题。

抑制相关的 CA1820 警告是否安全?

编辑:更新了代码示例和文本以更好地反映我的情况。

编辑:这是(稍作修改的)实际代码(位于标准 IXmlSerialized 实现中):

public void ReadXml (XmlReader reader)
    // ...
    string img = reader.ReadElementString ("Image");
    if (img != "") {
        Image = Image.FromFile(img);
    }
    // ...

I've got code similar to this:

string s = CreateString();
if (s == "") foo(s);

If s equals "", foo should be called. If string is null, which should never happen, then a NullReferenceException is fine (as this is, after all, an exceptional situation).

CodeAnalysis tells me to test for s.IsNullOrEmpty. This would alter the functionality in a nunintended way.

Performance is not an issue.

Is it safe to suppress the associated CA1820 warning?

Edit: Updated code sample and text to better reflect my case.

Edit: This is the (slightly altered) actual code (it's in a standard IXmlSerializable implementation):

public void ReadXml (XmlReader reader)
    // ...
    string img = reader.ReadElementString ("Image");
    if (img != "") {
        Image = Image.FromFile(img);
    }
    // ...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

£烟消云散 2024-08-16 21:20:53

最好将测试编写为:

if(s != null && s == "")

然后您可以在另一个 if 语句中处理空值

It would be better to write the test as:

if(s != null && s == "")

You can then process a null value in another if statement

暖心男生 2024-08-16 21:20:53

您并没有真正忽略该警告,您已经查看了代码并确定该警告不适用。这是抑制警告的完全合理的条件。

纯粹的猜测

不过,我希望我能更多地了解你想要做什么。我怀疑可能有更好的方法来处理它。该模式提醒我返回错误消息或空以表示方法成功。如果是这种情况,我会考虑返回 void 并在失败时抛出异常,或者返回 bool 并仅在消息关键时抛出异常,否则返回 true/false。

You're not really ignoring the warning, you've looked at the code and decided that the warning doesn't apply. This is a perfectly reasonable condition under which to suppress the warning.

Pure Speculation

I wish I knew a little more about what you were trying to do, however. I suspect that there may be a better way to handle it. The pattern reminds me of returning an error message or empty to signal the success of a method. If that's the case, I would consider either returning void and throwing an exception on failure or returning bool and only throwing exceptions when the message is critical and returning true/false otherwise.

待天淡蓝洁白时 2024-08-16 21:20:53

如果 null 可以,那么无论哪种方式都可以。

If null is OK, you'll be fine either way.

郁金香雨 2024-08-16 21:20:53

是的。

但我同意使用 string.IsnullOrEmpty 进行 CodeAnalysis 是一个安全的选择。

yes.

But i would agree with CodeAnalysis with string.IsnullOrEmpty is a safe choice.

梦忆晨望 2024-08-16 21:20:53

Can 时不处理异常通常是一个坏主意,因此 CA 是正确的,因为您要么需要将 null 视为空,要么处理异常。使用返回值引起的空引用异常是一件非常糟糕的事情。至少放入 Debug.Assert(s!=null) 并与 string.Empty 进行比较

Not handling exception whereas you Can is gennerally a bad idea so CA is right in that you either need to treat null as empty or handle the exception. A null reference exception caused by using a return value is a very bad thing. At the very least put in a Debug.Assert(s!=null) and compare to string.Empty

想挽留 2024-08-16 21:20:52

对于空值,它的行为会有所不同,因此这取决于您想要发生的情况;您提到 NullReferenceException 是可以的,但是引用的代码中没有任何内容会引发此问题,因此它可能会导致下游出现意外错误。

我从来没有,但我总是想添加:

static bool IsNullOrEmpty(this string value) {
    return string.IsNullOrEmpty(value);
}

所以我可以使用:

if (s.IsNullOrEmpty()) foo();

It will behave differently with regards to nulls, so it depends what you want to happen; you mention that NullReferenceException would be OK, but there is nothing in the code cited that would raise this, hence why it could cause unexpected errors downstream.

I never have, but I'm always tempted to add:

static bool IsNullOrEmpty(this string value) {
    return string.IsNullOrEmpty(value);
}

so I can use:

if (s.IsNullOrEmpty()) foo();
仙气飘飘 2024-08-16 21:20:52

规格:

如果 s 等于 "",则应调用 foo。
如果字符串为空,则永远不应该
发生,然后出现 NullReferenceException
没问题。

只需按照 CodeAnalysis 规则中的建议测试字符串长度

if (s.Length == 0) foo(s);

您的问题:

压制相关的内容是否安全?
CA1820警告?

您可以忽略它,您的代码可以工作,但我不建议这样做,请尽可能遵循指南。即使主题(性能)不是问题,您的代码也会更加一致,并且您习惯于编写标准代码。

Specs :

If s equals "", foo should be called.
If string is null, which should never
happen, then a NullReferenceException
is fine.

Just test the string length as adviced in the CodeAnalysis rule :

if (s.Length == 0) foo(s);

Your question :

Is it safe to suppress the associated
CA1820 warning?

You can ignore it, your code will work but I wouldn't advice it, follow the guidelines as much as you can. Even if the topic (performance) is not an issue, your code will be more consistent and you get accustomed to write standard code.

熟人话多 2024-08-16 21:20:52

每个代码分析警告都有关联的文档,您可以通过突出显示警告并按 F1 来访问这些文档。您还可以右键单击该项目来获取帮助。

无论如何,这里有解释该特定警告的文档

根据该文档,“如果性能不是问题,则可以安全地抑制此规则的警告”。

Every Code Analysis warning has associated documentation that you can access by highligting the warning and pressing F1. You can also right-click on the item to get help.

In any case, here's the documentation that explains that particular warning.

According to that documentation, it is "safe to suppress a warning from this rule if performance is not an issue".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文