"布尔"为对象VS"串"为对象测试相等 [英] "bool" as object vs "string" as object testing equality

查看:145
本文介绍了"布尔"为对象VS"串"为对象测试相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是比较新的C#,我发现了一些有趣的今天,我想我从来没有注意到或者我失去了一些东西。下面是一个NUnit测试举一个例子:

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);

我不是在其本身的第一个失败看到,因为boolean1和惊讶,boolean2是不同的参考。但它是困扰到我说的第一个发生故障,而第二个通过。我读(MSDN上的某个地方)一些魔法做的目的是String类,以促进这一点。我想我的问题其实就是没有这种行为复制到布尔?作为一个音符......如果boolean1和2被声明为布尔则是没有问题的。

什么是这些差异的原因,或者为什么它被执行呀?是否有一个情况下,你会在这里想引用一个布尔值,对象为任何东西,除了它的价值呢?

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?

推荐答案

这是因为字符串其实都是指的同一个实例。串被扣留,使得唯一的字符串被重用。这意味着,在code中,两个字符串变量将引用相同的,实习串实例

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)

更新
只是为了保持完整性;安东尼指出字符串的文本的被拘留,可以用下面的code表明:

Update
Just for completeness; as Anthony points out string literals are interned, which can be showed with the following code:

object firstString = "string1";
object secondString = "string1";
Console.WriteLine(firstString == secondString); // prints True

int n = 1;
object firstString = "string" + n.ToString();
object secondString = "string" + n.ToString();
Console.WriteLine(firstString == secondString); // prints False

这篇关于"布尔"为对象VS"串"为对象测试相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆