c# - 为什么我可以将空条件运算符应用于硬编码字符串?

标签 c# string visual-studio-2015 null-conditional-operator

我有一个像这样的 bool 变量:

bool myBool = true;

如果我写 if (myBool == null) 我会收到以下警告:

The result of the expression is always 'false' since a value of type 'bool' is never equal to 'null' of type 'bool?'.

这对我来说很清楚,因为检查不可为 null 的变量是否为 null 没有意义。 Visual Studio 注意到这一点并将其标记为警告。

现在我有一个 string,据我所知,它在默认情况下可以为 null。

为什么我可以在 Visual Studio 不注意的情况下将 null 条件运算符应用于硬编码的 string?我在想这样的事情:

"This is a string"?.AnyStringMethod();

Visual Studio 难道不应该注意到这个 string 根本不是 null 吗?

最佳答案

警告是针对看起来正确但实际上错误的代码

您的代码看起来不对,但无论如何都是正确的

因此:没有警告。

关于c# - 为什么我可以将空条件运算符应用于硬编码字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38076413/

相关文章:

c# - Visual Studio 2015 中没有生成 pdb

c# - 从 C# 调用对话窗口

C - 将 X 长度的字符串拆分/存储到结构数组中

visual-studio-2015 - Visual Studio 2015 - 运行测试失败并陷入循环

python - 按长度和最后 N 个字符对字符串列表进行排序

java - 检测 utf8mb4 字符集要求

visual-studio-2015 - 无法在 Visual Studio 2015 中打开 .cshtml 文件

c# - 本地化 Windows Phone 8 应用程序图标和平铺图像

c# - 具有多字符替换的字符串组合

C# 事件目录 : Get domain name of user?