今天写程序时发生了这样一个问题,调试的时候和运行时的结果不同,查了半天原来是因为调试的时候点击变量会自动调用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行设断点,就会得到不同的结果