类与结构是C#程序设计中基本的数据类型,而初学者往往不能很好的分清二者之间的区别。本文就以附带实例形式加以说明。具体如下:
一、基本概念:
类:引用类型,存储在堆中,栈中存储引用地址,在方法的传输中只是传输地址的引用,修改指向的对象会影响原有对象的值,传输中消耗内存小。
结构:值类型,存储在堆栈中,传输过程中传输整个对象的副本,修改指向对象的值不会影响原有的对象,传输中消耗内存大。
二、实例代码如下:
class Program{ static void Main(string[] args) { TestClass TC1 = new TestClass(); TC1.x = 10; TC1.y = "10"; Console.WriteLine(""); Console.WriteLine("TC1 x={0} y={0}", TC1.x, TC1.y); TC1.x = 20; TC1.y = "20"; Console.WriteLine(""); Console.WriteLine("TC1 x={0} y={0}", TC1.x, TC1.y); Console.WriteLine(""); TestClass TC2 = TC1; TC2.x = 10; TC2.y = "10"; Console.WriteLine(""); Console.WriteLine("TC1 x={0} y={0}", TC1.x, TC1.y); Console.WriteLine("TC2 x={0} y={0}", TC2.x, TC2.y); Console.WriteLine(""); TestStruct TS1 = new TestStruct(); TS1.x = 10; TS1.y = "10"; Console.WriteLine("TS1 x={0} y={0}", TS1.x, TS1.y); Console.WriteLine(""); TS1.x = 20; TS1.y = "20"; Console.WriteLine("TS1 x={0} y={0}", TS1.x, TS1.y); Console.WriteLine(""); TestStruct TS2 = TS1; TS2.x = 10; TS2.y = "10"; Console.WriteLine(""); Console.WriteLine("TS1 x={0} y={0}", TS1.x, TS1.y); Console.WriteLine("TS2 x={0} y={0}", TS2.x, TS2.y); Console.ReadLine(); }}public class TestClass{ public int x; public string y;}public struct TestStruct{ public int x; public string y;}代码运行结果如下图所示: