C# 中的 Struct v/s Class - 请解释行为 [英] Struct v/s Class in C# - Please explain the behavior
问题描述
谁能解释一下这种行为
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
*/
为什么我的类的输出与结构的输出不同?
Why am I not getting the same output for a class as that of a struct?
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
*/
推荐答案
类是引用类型,结构是值类型.
Classes are reference types, structs are value types.
当值类型作为参数传递给方法时,它的副本将被传递.这意味着您要添加 Person
结构的两个完全独立的副本,循环中的每一次通过一个副本.
When a value type is passed to a method as a parameter, a copy of it will be passed through. That means that you add two completely separate copies of the Person
struct, one for each pass in the loop.
当引用类型作为参数传递给方法时,引用将被传递.这意味着您将引用的两个副本添加到同一个内存位置(到同一个 Person
对象) - 当对这个对象进行更改时,您会看到它反映在两个引用,因为它们都引用同一个对象.
When a reference type is passed to a method as a parameter, the reference will be passed through. That mean that you add two copies of the reference to the same memory location (to the same Person
object) - when making changes to this one object, you see it reflected in both references since they both reference the same object.
这篇关于C# 中的 Struct v/s Class - 请解释行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!