谁能解释一下这个行为
class testCompile
{
/*
* Sample Code For Purpose of Illustration
*/
struct person
{
public int age;
public string name;
}
static void Main(string[] args)
{
List<person> Listperson = new List<person>();
person myperson = new person();
for (int i = 1; i <= 2; i++)
{
//Assignment
myperson.age = 22+i;
myperson.name = "Person - " + i.ToString();
Listperson.Add(myperson);
}
int x = 0;
while (x < Listperson.Count)
{
//Output values
Console.WriteLine("{0} - {1}", Listperson[x].name, Listperson[x].age);
x++;
}
}
}
/*
Output:
Person - 1 - 23
Person - 2 - 24
*/
为什么类的输出与结构的输出不同?
class testCompile
{
/*
* Sample Code For Purpose of Illustration
*/
class person
{
public int age;
public string name;
}
static void Main(string[] args)
{
List<person> Listperson = new List<person>();
person myperson = new person();
for (int i = 1; i <= 2; i++)
{
//Assignment
myperson.age = 22+i;
myperson.name = "Person - " + i.ToString();
Listperson.Add(myperson);
}
int x = 0;
while (x < Listperson.Count)
{
//Output values
Console.WriteLine("{0} - {1}", Listperson[x].name, Listperson[x].age);
x++;
}
}
}
/*
Output:
Person - 2 - 24
Person - 2 - 24
*/
最佳答案
类是引用类型,结构是值类型。
当值 类型作为参数传递给方法时,它的副本 将被传递。这意味着您添加了 Person
结构的两个完全独立的副本,一个用于循环中的每个传递。
当引用 类型作为参数传递给方法时,引用 将被传递。这意味着您添加了两个对相同内存位置的引用的副本(到相同的 Person
对象) - 当对这个对象进行更改时,您会看到它反射(reflect)在两个引用,因为它们都引用同一个对象。
关于c# - C# 中的结构与类 - 请解释行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3924054/