簡體   English   中英

為什么在 C# 中使用 String Builder 關鍵字時 memory 地址不同?

[英]Why is there a difference in memory address when using String Builder keyword in C#?

根據使用 String Builder 關鍵字手動調整字符串后的理論,兩個 memory 地址必須相同,但我得到了錯誤的答案。 誰能解釋一下。

class Program
    {             
        static void Main(string[] args)
        {
            Console.WriteLine("using string keyword (immutable)");
            string str1 = "Interview";
            Console.WriteLine("str1 text is: "+ str1);
            unsafe
            {
                fixed (char* pointer = str1)
                {
                    Console.WriteLine("Memory address of str1 is: "+(int)pointer);
                }
                
            }

            str1 += "Happy";
            Console.WriteLine("str1 modified text is: "+str1);
            unsafe
            {
                fixed (char* pointer = str1)
                {
                    Console.WriteLine("str1 memeory address is: "+(int)pointer);
                }

            }
            Console.WriteLine("\n");
            Console.WriteLine("Using String Builder to (mutable string)");
            StringBuilder str2 = new StringBuilder();

            str2.Append ("Interview");
            Console.WriteLine("str2 text is:" + str2);
            unsafe
            {
                fixed (char* pointer = str2.ToString())
                {
                    Console.WriteLine("str2 memory address is: "+(int)pointer);
                }
            }
           
            str2.Append("Selection Process");
            Console.WriteLine("str2 modified text is: "+str2);
            unsafe
            {
                fixed (char* pointer = str2.ToString())
                {
                    Console.WriteLine("str2 aftermodified memory address is:"+(int)pointer);
                }
            }
            Console.ReadKey();
        }
    }

// result
using string keyword (immutable)
str1 text is: Interview
Memory address of str1 is: 52066096
str1 modified text is: InterviewHappy
str1 memeory address is: 52069440


Using String Builder to (mutable string)
str2 text is:Interview
str2 memory address is: 52070212
str2 modified text is: InterviewSelection Process
str2 aftermodified memory address is:52070828

我認為通過使用 string Builder key wor 在兩個場景中結果相同,但結果與預期不同。

結果是

使用字符串關鍵字(不可變) str1 文本為:Interview Memory str1 的地址為:52066096 str1 修改后的文本為:InterviewHappy str1 內存地址為:52069440

Using String Builder to (mutable string) str2 text is:Interview str2 memory address is: 52070212 str2 modified text is: InterviewSelection Process str2 aftermodified memory address is:52070828

How does StringBuilder work internally in C#? 部分回答了您的問題?

答案的rest是:

如果可以在不執行新分配的情況下完成您正在執行的操作,Stringbuilder可能會返回相同的地址。 保證返回相同的地址。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM