Atu*_*eka 3 .net c# string operators
请考虑以下代码:
public static void Main()
{
string str1 = "abc";
string str2 = "abc";
if (str1 == str2)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
输出为"True".string是.Net中的引用类型我正在比较两个不同的对象,但输出仍为"True".
ToString()在两个对象上内部调用方法并在比较它们之前?string是不可变类型?具有相同值的两个完全不同的 string对象将指向堆上的相同内存位置?string比较是如何发生的?
内存分配如何在堆上运行?string具有相同值的两个不同对象是指向相同的内存位置还是指向不同的内存位置?
所以现在你应该能够理解为什么你在这个程序片段中得到给定的输出:
string a1 = "a";
string a2 = "a";
string aa1 = a1 + a2;
string aa2 = a1 + a2;
object o1 = a1;
object o2 = a2;
object o3 = aa1;
object o4 = aa2;
Console.WriteLine(a1 == a2); // True
Console.WriteLine(aa1 == aa2); // True
Console.WriteLine(o1 == o2); // True
Console.WriteLine(o3 == o4); // False
Run Code Online (Sandbox Code Playgroud)
那有意义吗?
对于字符串类型,==比较字符串的值.
请参阅http://msdn.microsoft.com/en-us/library/53k8ybth.aspx
关于你关于寻址的问题,几行代码说它们将具有相同的地址.
static void Main(string[] args)
{
String s1 = "hello";
String s2 = "hello";
String s3 = s2.Clone() as String;
Console.Out.WriteLine(Get(s1));
Console.Out.WriteLine(Get(s2));
Console.Out.WriteLine(Get(s3));
s1 = Console.In.ReadLine();
s1 = Console.In.ReadLine();
s3 = s2.Clone() as String;
Console.Out.WriteLine(Get(s1));
Console.Out.WriteLine(Get(s2));
Console.Out.WriteLine(Get(s3));
}
public static string Get(object a)
{
GCHandle handle = GCHandle.Alloc(a, GCHandleType.Pinned);
IntPtr pointer = GCHandle.ToIntPtr(handle);
handle.Free();
return "0x" + pointer.ToString("X");
}
Run Code Online (Sandbox Code Playgroud)
每组测试的结果都在相同的地址中.