结构体和类同样能够定义字段,方法和构造函数,都能实例化对象,这样看来结构体和类的功能好像是一样的了,但是他们在数据的存储上是不一样的(以下摘录):
C#结构体和类的区别问题:在C#编程语言中,类属于引用类型的数据类型,结构体属于值类型的数据类型,这两种数据类型的本质区别主要是各自指向的内存位置不同。传递类的时候,主要表现为是否同时改变了源对象。
C#结构体和类的区别技术要点:
◆类在传递的时候,传递的内容是位于托管内存中的位置,结构体在传递的时候,传递的内容是位于程序堆栈区的内容。当类的传递对象修改时,将同时修改源对象,而结构体的传递对象修改时,不会对源对象产生影响。
◆在一个类中,可以定义默认的、不带参数的构造函数,而在结构体中不能定义默认的、不带参数的构造函数。两者都可以定义带有参数的构造函数,通过这些参数给各自的字段赋值或初始化
代码运行如下:类中赋值以后,两个对象中的值都发生变化,而结构体原来对象的值为发生变化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100 |
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.Name = "刘翔" ; Liuxiang.Age = 30; Liuxiang.Sex = 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; } } } |
原文:http://www.cnblogs.com/jameslif/p/3593932.html