c# - StringBuilder("...").ToString() 和 new String() 的行为不同。为什么?
问题描述
在以下测试中:str == str2
和的结果如何x == y
不同?
[Test]
public void StringsAreImmutableObjects()
{
String str = new String(new char[] {'a', 'l', 'i'});
String str2 = new String(new char[] {'a', 'l', 'i'});
Assert.AreEqual("ali", str);
Assert.AreEqual("ali", str2);
/*
* Strange!
*
* C# has two "equals" concepts: Equals and ReferenceEquals.
* For most classes you will encounter, the == operator uses
* one or the other (or both), and generally only tests for
* ReferenceEquals when handling reference types (but the
* string Class is an instance where C# already knows how
* to test for value equality).
*/
Assert.AreEqual(str, str2);
Assert.IsTrue(str == str2);
Assert.IsTrue(Equals(str, str2));
Assert.IsFalse(ReferenceEquals(str, str2));
object x = new StringBuilder("hello").ToString();
object y = new StringBuilder("hello").ToString();
Assert.IsTrue(x.Equals(y));
Assert.IsTrue(object.Equals(x, y));
Assert.IsFalse(x == y);
Assert.IsFalse(ReferenceEquals(x, y));
}
以下测试也将通过:
Assert.IsTrue(str is string);
Assert.IsTrue(str2 is string);
Assert.IsTrue(x is string);
Assert.IsTrue(y is string);
解决方案
推荐阅读
- html - 验证字符串在 r 中是 html/xml
- python - 使用 Numpy 将表格行数据相乘
- qt - Text2DEntity 呈现不透明并隐藏其后的其他实体
- javascript - React 身份验证会话管理
- mysql - 在 mySQL / phpmyadmin 中创建新列的问题
- php - 在 Laravel 中向作业添加参数后失败
- identityserver4 - IdentityServer4:“Microsoft.Build.Tasks.Git.LocateRepository”任务意外失败
- python - 初学者python问题:函数参数中未解析的引用(传递变量)
- erlang - 简单的 Elixir / Plug 进程问题 - PID 不存在
- java - 使用 XSLT 3.0 将 JSON 转换为 XML