为什么Assert.AreSame()认为两个单独的字符串相同?

问题描述 投票:1回答:1

为什么要通过Assert.AreSame()

[TestMethod]
public void StringSameTest()
{
      string a = "Hello";
      string b = "Hello";

      Assert.AreSame(a, b);
}

我了解引用相等性的测试,并且与Assert.IsTrue(object.ReferenceEquals(a, b))基本相同,但是很明显ab是不同的字符串对象,无论它们具有相同的值是什么。如果将string b = a;设置为will intern identical literal strings,则期望为true,但事实并非如此。为什么该测试不失败?

谢谢

c# string unit-testing mstest
1个回答
3
投票

C#编译器String.Copy()对相同的const字符串引用。

要创建与const字符串相同的单独字符串实例,请使用String.Clone()(请注意,String.ToString()返回对自身的引用,and that there is no legitimate need for String.Copy().String.Copy()也是如此。

string a = "Hello";
string b = a.Copy();

Assert.AreSame(a, b); // false

请参见Do string literals get optimised by the compiler?

© www.soinside.com 2019 - 2024. All rights reserved.