using System;
using System.Collections.Generic;
using System.Text;namespace StructByValue
{
    struct Student
    {
        private int _age;
        public Student()
        {
            
        }
        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }
    }    class Program
    {
        static void Main(string[] args)
        {
            //Student student = new Student(20);
            Student student=new Student();
            student.Age = 20;
            Console.WriteLine("更新年龄之前的结果是:{0}", student.Age); 
            Program.ChangeAge(student);
            Console.WriteLine("更新年龄之后的结果是:{0}", student.Age);         }
        static void ChangeAge(Student student)
        {
            student.Age = 37;
        }    }
}
这样调用为什么输出的值怎么都是 20;

解决方案 »

  1.   

     struct Student
        {
            private int _age;
            public int Age
            {
                get { return _age; }
                set { _age = value; }
            }
        }
    static void ChangeAge(ref Student student)
            {
                student.Age = 37;
            }
      

  2.   

    上述写法换成类的话,就可以,为什么?
    class Student
        {
            private int _age;
            public Student()
            {
                
            }
            public int Age
            {
                get { return _age; }
                set { _age = value; }
            }
        }
      

  3.   

    结构是值类型 -- 如果从结构创建一个对象并将该对象赋给某个变量,变量则包含结构的全部值。复制包含结构的变量时,将复制所有数据,对新副本所做的任何修改都不会改变旧副本的数据。由于结构不使用引用,因此结构没有标识 -- 具有相同数据的两个值类型实例是无法区分的。C# 中的所有值类型本质上都继承自 ValueType,后者继承自 Object。