c# - C# 中的结构与类 - 请解释行为

标签 c# .net class struct

谁能解释一下这个行为

  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/

相关文章:

c# - 多播委托(delegate)是否为每个链接创建新的引用?

c# - 如何在 C# 中正确地多次分割/除一个整数?

c# - 部署小型 .NET 3.5 应用程序时出现的问题

c# - 将 '[' 8 个字符 ']' 替换为空白

c# - 类设计指南中的算术运算符和方法

c++ - 如何输出乘以用户创建的类c++

c# - 在 EF6 中延迟加载任何内容时如何记录

c# - Recommender.GetRecommendedSymbolsAtPositionAsync 返回太多符号

c# - 包含来自网络的动态库

function - Lua函数参数是如何传递的?