using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string str1 = "HelloWorld";
string str2 = "HelloWorld";
//Console.WriteLine(str1 == str2);
//Console.WriteLine(str1.Equals(str2));
Console.WriteLine((object)str1 == (object)str2);//True
Console.ReadKey();
}
}
}
是不是所有值为"HelloWorld"的字符串变量都指向同一对象,那字符串副本又是怎么回事?
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string str1 = "HelloWorld";
string str2 = "HelloWorld";
//Console.WriteLine(str1 == str2);
//Console.WriteLine(str1.Equals(str2));
Console.WriteLine((object)str1 == (object)str2);//True
Console.ReadKey();
}
}
}
是不是所有值为"HelloWorld"的字符串变量都指向同一对象,那字符串副本又是怎么回事?
因为都是开发时候写死的,代码优化时候,编译之后,str1和str2指向的就是同一个常量字符串被,运行时被放在字符串池中了。Equals是比较值是否相等== 是比较是否引用相同,你这里是常量,所以是相同的。
如果你一个是str1的常量方式制定,另一个是console.readline获得,虽然输入一样,但还是引用不同。因为运行时的字符串,多个并不会放入字符串池,一定要放,需要调用string的方法。
string b = "h";
// Append to contents of 'b'
b += "ello";
Console.WriteLine(a == b);
Console.WriteLine((object)a == (object)b);这将先显示“True”,然后显示“False”,因为字符串的内容是相同的,但是 a 和 b 引用的不是同一个字符串实例。
string(C# 参考)