C# 可能的意外参考比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12263715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:40:50  来源:igfitidea点击:

Possible unintended reference comparison

c#

提问by user3357963

I have the following code which gives a warning

我有以下代码发出警告

Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'`

可能的意外参考比较;要进行值比较,请将左侧强制转换为“字符串”

if (lblStatus.Content == "ACTIVE")
{
  //Do stuff
}
else
{
  //Do other Stuff
}

I'm assuming the warning is because lblStatus.Contentmay not necessarily always be of type string?

我假设警告是因为lblStatus.Content可能不一定总是字符串类型?

I've tried to fix it using each of the following but I still get a warning

我已经尝试使用以下每个方法修复它,但我仍然收到警告

if (lblStatus.Content.ToString() == "ACTIVE")
if ((string)lblStatus.Content == "ACTIVE")
if (lblStatus.Content === "ACTIVE")

Please could someone explain the reason I still get a warning and the best practical way to deal with this?

请有人解释我仍然收到警告的原因以及处理此问题的最佳实用方法吗?

采纳答案by Jon Skeet

The warning is because the compile-timetype of lblStatus.Contentis object. Therefore operator overloading chooses the ==(object, object)overload which is just a reference identity comparison. This has nothing to do with what the execution-timetype of the value is.

警告是因为 的编译时类型lblStatus.Contentobject. 因此,运算符重载选择==(object, object)只是一个引用标识比较的重载。这与值的执行时间类型无关。

The first or second of your options shouldhave fixed the warning though:

不过,您的第一个或第二个选项应该已修复警告:

if (lblStatus.Content.ToString() == "ACTIVE")
if ((string)lblStatus.Content == "ACTIVE")

Note that the first of these will throw an exception if lblStatus.Contentis null. I would prefer the second form.

请注意,如果lblStatus.Content为空,其中第一个将引发异常。我更喜欢第二种形式。

If you think you're still seeing a warning at that point, I suspect you either haven't rebuilt - or something is still "dirty" in your build. A full rebuild absolutelyshould remove the warning.

如果您认为此时您仍然看到警告,我怀疑您要么没有重建 - 或者您的构建中仍有一些“脏”。完全重建绝对应该消除警告。

回答by alex.b

I prefer to stick the string.Equals(string,string,StringComparison)method, like the following:

我更喜欢坚持该string.Equals(string,string,StringComparison)方法,如下所示:

    string contentStr = (lblStatus.Content ?? string.Empty).ToString();
    if (string.Equals("ACTIVE", contentStr, StringComparison.OrdinalIgnoreCase))
    { 
        // stuff
    } 

because it explicitely states what it does + it doesn't give a warning you've mentioned.

因为它明确说明了它的作用+它没有给出你提到的警告。

回答by user3562690

Rebuild your project after you fix your code with this :

使用以下方法修复代码后重建项目:

if (lblStatus.Content.ToString() == "ACTIVE")
if ((string)lblStatus.Content == "ACTIVE")
if (lblStatus.Content === "ACTIVE")