Why doesn#39;t the compiler at least warn on this == null(为什么编译器至少对此 == null 不发出警告)
问题描述
为什么 C# 编译器甚至不抱怨这段代码的警告?:
Why does the C# compiler not even complain with a warning on this code? :
if (this == null)
{
// ...
}
显然条件将永远得到满足..
Obviously the condition will never be satisfied..
推荐答案
因为你可以覆盖 operator == 以针对这种情况返回 true.
Because you could override operator == to return true for that case.
public class Foo
{
public void Test()
{
Console.WriteLine(this == null);
}
public static bool operator ==(Foo a, Foo b)
{
return true;
}
public static bool operator !=(Foo a, Foo b)
{
return true;
}
}
运行 new Foo().Test() 将在控制台打印True".
Running new Foo().Test() will print "True" to the console.
这里的另一个问题是:为什么编译器不为 ReferenceEquals(this, null) 发出警告?从上面链接的底部:
The other question here is: why doesn't the compiler issue a warning for ReferenceEquals(this, null)? From the bottom of the above link:
operator == 重载的一个常见错误是使用 (a == b), (a == null),或 (b == null) 来检查引用是否相等.这反而会导致调用重载的 operator ==,从而导致无限循环.使用 ReferenceEquals 或将类型转换为 Object,以避免循环.
A common error in overloads of
operator ==is to use(a == b),(a == null), or(b == null)to check for reference equality. This instead results in a call to the overloadedoperator ==, causing an infinite loop. UseReferenceEqualsor cast the type to Object, to avoid the loop.
那个可能会由@Aaronaught 的回复来回答.这也是为什么你应该做 (object)x == null 或 ReferenceEquals(x, null),而不是做一个简单的 x == null,当您检查空引用时.当然,除非您确定 == 运算符没有重载.
That might be answered by @Aaronaught's response. And that's also why you should be doing (object)x == null or ReferenceEquals(x, null), not doing a simple x == null, when you're checking for null references. Unless, of course, you're sure that the == operator is not overloaded.
这篇关于为什么编译器至少对此 == null 不发出警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么编译器至少对此 == null 不发出警告
基础教程推荐
- 获取C#保存对话框的文件路径 2022-01-01
- 如果条件可以为空 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 将数据集转换为列表 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 从 C# 控制相机设备 2022-01-01
