c# – 类型字符串的引用对象比较
发布时间:2020-12-16 00:09:01 所属栏目:百科 来源:网络整理
导读:请考虑以下代码: public static void Main(){ string str1 = "abc"; string str2 = "abc"; if (str1 == str2) { Console.WriteLine("True"); } else { Console.WriteLine("False"); } Console.ReadLine();} 输出为“True”. string是.Net中的引用类型.我正
请考虑以下代码:
public static void Main() { string str1 = "abc"; string str2 = "abc"; if (str1 == str2) { Console.WriteLine("True"); } else { Console.WriteLine("False"); } Console.ReadLine(); } 输出为“True”. string是.Net&中的引用类型.我正在比较两个不同的对象,但输出仍为“True”. >是因为它在内部调用两个对象上的ToString()方法&在比较它们之前? 字符串比较是如何发生的? 内存分配如何在堆上运行?两个具有相同值的不同字符串对象是指向相同的内存位置,还是指向不同的内存位置? 解决方法
见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"); } 每组测试的结果都在相同的地址中. 得到()诉讼于Memory address of an object in C# (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |