Eri*_*ric 2 c# variables winforms
我将a的值赋给了variableA另一种形式variableB.为什么两个变量都是空的,之后我清除了variableA?
Before execute entries.clear()
Run Code Online (Sandbox Code Playgroud)
After execute entries.clear()
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 22
双方frm5.entries并entries指向同一个对象,由于这种代码前面:
frm5.entries = entries;
Run Code Online (Sandbox Code Playgroud)
这里每个变量的值只是对象的引用 - 就像两张纸上有相同的房子地址.你打电话entries.Clear()的时候就像是说:"带着写在纸上的地址去看房子entries,取出所有的家具." 如果你带着写在纸上的地址去了房子frm5.entries,你会看到一个空房子.
这就是引用类型在.NET中的工作方式,了解这一点对于在任何.NET语言中取得进展至关重要.我有一个关于该主题的页面,其中包含更多信息,并且您可能会发现Stack Overflow问题也很有用.
这是一个证明这一点的例子:
using System;
using System.Collections.Generic;
class Test
{
static void Main()
{
List<string> x = new List<string>();
List<string> y = x;
// x and y now refer to the same list...
x.Add("foo");
Console.WriteLine(y.Count); // 1
y.Clear();
Console.WriteLine(x.Count); // 0
// Changing x or y to refer to a different list
// *doesn't* change the other variable
x = new List<string>();
x.Add("bar");
x.Add("baz");
Console.WriteLine(y.Count); // 0
}
}
Run Code Online (Sandbox Code Playgroud)