C#中类和结构体的区别
[来源] 达内 [编辑] 达内 [时间]2012-11-01
结构体和类同样能够定义字段,方法和构造函数,都能实例化对象,这样看来结构体和类的功能好像是一样的了,但是他们在数据的存储上是不一样的
结构体和类同样能够定义字段,方法和构造函数,都能实例化对象,这样看来结构体和类的功能好像是一样的了,但是他们在数据的存储上是不一样的(以下摘录):
C#结构体和类的区别问题:在C#编程语言中,类属于引用类型的数据类型,结构体属于值类型的数据类型,这两种数据类型的本质区别主要是各自指向的内存位置不同。传递类的时候,主要表现为是否同时改变了源对象。
C#结构体和类的区别技术要点:
◆类在传递的时候,传递的内容是位于托管内存中的位置,结构体在传递的时候,传递的内容是位于程序堆栈区的内容。当类的传递对象修改时,将同时修改源对象,而结构体的传递对象修改时,不会对源对象产生影响。
◆在一个类中,可以定义默认的、不带参数的构造函数,而在结构体中不能定义默认的、不带参数的构造函数。两者都可以定义带有参数的构造函数,通过这些参数给各自的字段赋值或初始化
代码运行如下:类中赋值以后,两个对象中的值都发生变化,而结构体原来对象的值为发生变化
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 类对象 { // 枚举 public enum Gender { 男, 女 } //结构体 public struct stuPerson { public string stuName; public int stuAge; public Gender stuSex; public void stuSayHello() { Console.WriteLine( " 我是{0},年龄{1},性别{2} " , stuName, stuAge, stuSex); } // 必须定义有参数的构造函数 public stuPerson( string name, int age, Gender sex) { this .stuName = name; this.stuAge = age; this.stuSex = sex; } } class Program { static void Main(string [] args) { // 实例化类 Person Liuxiang = new Person(); // 无参数的构造函数实例化的对象 = " 刘翔" ; Liuxiang.Age = 30 ; = Gender.男; Liuxiang.SayHello(); //声明另一个实例 Person LXSon = Liuxiang; LXSon.Age = 10; // 查看类 LiuXiang 和 LXSon中字段的值 Console.WriteLine(" LiuXiang 年龄{0}" , Liuxiang.Age.ToString()); // 10 Console.WriteLine(" LXSon 年龄{0}" , LXSon.Age.ToString()); // 10 Console.WriteLine(); //结构体 stuPerson YaoMing = new stuPerson("姚明 ",33 ,Gender.男); YaoMing.stuSayHello(); stuPerson YMSon = YaoMing; YMSon.stuAge = 13; // 查看结构体中 YaoMing 和 YMSon中字段的值 Console.WriteLine(" YaoMing 年龄{0}" , YaoMing.stuAge.ToString()); // 10 Console.WriteLine(" YMSon 年龄{0}" , YMSon.stuAge.ToString()); // 10 Console.ReadLine(); } } class Person { //定义字段 public string Name; public int Age; public Gender Sex; //定义方法 public void SayHello() { Console.WriteLine( " 我是{0},年龄{1},性别{2} ", this .Name, this.Age, this .Sex); } // 无参数的构造函数 public Person() { } // 有参数的构造函数 public Person(string name, int age, Gender sex) { this .Name = name; this.Age = age; this.Sex = sex; } } }