不應該在ToString()方法中修改參考型別

來源:互聯網
上載者:User

今天寫程式時發生了這樣一個問題,調試的時候和運行時的結果不同,查了半天原來是因為調試的時候點擊變數會自動調用ToString(),並且不會響應ToString()中的斷點,而這個程式恰恰在ToString()中對參考型別進行了修改,我們這裡類比一下這個情境來說明這個問題:

Test類
 1 class Test
 2     {
 3         Dictionary<string, string> dictionary = new Dictionary<string, string>();
 4         public Test(Dictionary<string, string> dictionary)
 5         {
 6             this.dictionary = dictionary;
 7         }
 8         public override string ToString()
 9         {
10             dictionary.Remove("lfm");
11             StringBuilder sb = new StringBuilder();
12             foreach (var item in dictionary)
13             {
14                 sb.Append(item.Key);
15                 sb.Append(",");
16             }
17             return sb.ToString();
18         }
19         public string GetString()
20         {
21             StringBuilder sb = new StringBuilder();
22             foreach (var item in dictionary)
23             {
24                 sb.Append(item.Key);
25                 sb.Append(",");
26             }
27             return sb.ToString();
28         }
29     }

 

運行代碼
 1  static void Main(string[] args)
 2         {
 3             Dictionary<string, string> d = new Dictionary<string, string>();
 4             d.Add("lfm", "dd");
 5             d.Add("lfm1", "uu");
 6             Test test = new Test(d);
 7             
 8             Console.WriteLine(test.GetString());
 9 
10         }

如果在運行代碼的第6行設斷點,就會得到不同的結果

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.