为什么编译器至少不警告这个 == null
- 作者: 亖呉?盀
- 来源: 51数据库
- 2022-10-21
问题描述
为什么 C# 编译器甚至不抱怨此代码的警告?:
Why does the C# compiler not even complain with a warning on this code? :
if (this == null)
{
// ...
}
显然条件将永远被满足..
推荐答案
因为你可以 覆盖 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 overloaded operator ==, causing an infinite loop. Use ReferenceEquals or 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.
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
