我有一个像这样的 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/