string的相关细节
首先,string 是引用类型
那么
string s1 ="Hello World!!"
string s2 ="Hello World!!"
是否是相同的引用?
string s3=s1+"!";
string s4=s1+"!";
是否是相同的引用?
string s5 ="Hello World!!"
string s6="Hello "+"World!!"
是否是相同的引用?
string s7=s1+"";
string s8=s1+"";
是否是相同的引用?
string s9="";
string s10=string.Empty;
是否是相同的引用?
由于在string中 "=="已经被重载为对值的比较而不是对引用的比较,所以比较时请使用object.ReferenceEquals()
public class MyString
{
/// <summary>
/// ==在string的比较中被重载为对值的比较
/// </summary>
public void TheEqualMarks()
{
string s1 = "Hello";
string s2 = "Hello";
if (s1 == s2)
{
Console.WriteLine("== is true");
}
else
{
Console.WriteLine("== is False");
}
s1 += "World!";
s2 += "World!";
if (s1 == s2)
{
Console.WriteLine("== is true");
}
else
{
Console.WriteLine("== is False");
}
}
/// <summary>
/// 声明两个相同值的字符串时,其引用是相同的,
/// "Hello World!!"与"Hello "+"World!!"指向相同引用
/// 使用string的引用进行+操作符时,会返回不同的地址引用,例如s9,s10的比较
/// +""时,扔指向原来的引用
/// </summary>
public void TheReferenceEquals()
{
string s1 = "Hello";
string s2 = "Hello";
if (Object.ReferenceEquals(s1,s2))
{
Console.WriteLine("ReferenceEquals is true");
}
else
{
Console.WriteLine("ReferenceEquals is False");
}
s1 += "";
s2 += "";
if (Object.ReferenceEquals(s1, s2))
{
Console.WriteLine("used += \"\" ReferenceEquals is true");
}
else
{
Console.WriteLine("used += \"\" ReferenceEquals is False");
}
s1 += "World!";
s2 += "World!";
if (Object.ReferenceEquals(s1, s2))
{
Console.WriteLine("ReferenceEquals is true");
}
else
{
Console.WriteLine("ReferenceEquals is False");
}
string s3 = "Hello World!!";
string s4 = "Hello ";
string s5 = "World!!";
string s6 = "Hello " + "World!!";
string s7 = s4 + s5;
if (Object.ReferenceEquals(s3, s6))
{
Console.WriteLine("s3, s6 TheReferenceEquals is true");
}
else
{
Console.WriteLine("s3, s6 TheReferenceEquals is False");
}
if (Object.ReferenceEquals(s3, s7))
{
Console.WriteLine("s3, s7 TheReferenceEquals is true");
}
else
{
Console.WriteLine("s3, s7 TheReferenceEquals is False");
}
s1 = "Hello";
s2 = "Hello";
string s9 = s1 + s2;
string s10 = s1 + s2;
if (Object.ReferenceEquals(s9, s10))
{
Console.WriteLine("s9, s10 ReferenceEquals is true");
}
else
{
Console.WriteLine("s9, s10 ReferenceEquals is False");
}
}
public void TheEquals()
{
string s1 = "Hello";
string s2 = "Hello";
if (s1.Equals(s2))
{
Console.WriteLine("Equals is true");
}
else
{
Console.WriteLine("Equals is False");
}
s1 += "World!";
s2 += "World!";
if (s1.Equals(s2))
{
Console.WriteLine("Equals is true");
}
else
{
Console.WriteLine("Equals is False");
}
}
/// <summary>
/// string.Empty与""指向相同引用
/// </summary>
public void TheStringEmpty()
{
string s1 = string.Empty;
string s2 = "";
if(object.ReferenceEquals(s1,s2))
{
Console.WriteLine("string.Empty, \"\" ReferenceEquals is true");
}
}
}
运行结果如下
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则视为侵权。