“布尔”作为对象与“字符串”作为对象测试平等
我对 C# 比较陌生,今天我注意到一些有趣的事情,我想我从来没有注意到或者也许我错过了一些东西。下面是一个 NUnit 测试来举例:
object boolean1 = false;
object booloan2 = false;
Assert.That(boolean1 == booloan2);
这个单元测试失败了,但是这个通过了:
object string1 = "string";
object string2 = "string";
Assert.That(string1 == string2);
我对第一个测试失败并没有感到惊讶,因为 boolean1 和 boolean2 是不同的引用。但令我困扰的是,第一个失败了,第二个通过了。我(在 MSDN 上的某个地方)读到,对 String 类做了一些魔法来促进这一点。我认为我的问题实际上是为什么这种行为没有在 bool 中复制?请注意...如果 boolean1 和 2 被声明为 bool
那么就没有问题。
造成这些差异的原因是什么,或者为什么要这样实施?是否存在您想要引用 bool 对象以获取除其值之外的任何内容的情况?
I am relatively new to C#, and I noticed something interesting today that I guess I have never noticed or perhaps I am missing something. Here is an NUnit test to give an example:
object boolean1 = false;
object booloan2 = false;
Assert.That(boolean1 == booloan2);
This unit test fails, but this one passes:
object string1 = "string";
object string2 = "string";
Assert.That(string1 == string2);
I'm not that surprised in and of itself that the first one fails seeing as boolean1, and boolean2 are different references. But it is troubling to me that the first one fails, and the second one passes. I read (on MSDN somewhere) that some magic was done to the String class to facilitate this. I think my question really is why wasn't this behavior replicated in bool? As a note... if the boolean1 and 2 are declared as bool
then there is no problem.
What is the reason for these differences or why it was implemented that way? Is there a situation where you would want to reference a bool object for anything except its value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为这些字符串实际上引用的是同一个实例。字符串被保留,以便重复使用唯一的字符串。这意味着在您的代码中,两个字符串变量将引用同一个内部字符串实例。
您可以在这里阅读更多相关内容:.NET 和 C# 中的字符串 ( 作者:Jon Skeet)
更新
只是为了完整性;正如安东尼指出的,字符串文字是被保留的,可以用以下代码显示:
It's because the strings are in fact referring the same instance. Strings are interned, so that unique strings are reused. This means that in your code, the two string variables will refer to the same, interned string instance.
You can read some more about it here: Strings in .NET and C# (by Jon Skeet)
Update
Just for completeness; as Anthony points out string literals are interned, which can be showed with the following code:
运算符重载。
Boolean 类没有重载的 == 运算符。 String 类可以。
Operator Overloading.
The Boolean class does not have an overloaded == operator. The String class does.
正如 Fredrik 所说,您正在进行参考比较与布尔比较。字符串场景起作用的原因是因为 == 运算符已被重载以供字符串进行值比较。请参阅 MSDN 上的 System.String 页面。
As Fredrik said, you are doing a reference compare with the boolean comparison. The reason the string scenario works is because the == operator has been overloaded for strings to do a value compare. See the System.String page on MSDN.