首页 > 学院 > 开发设计 > 正文

C#学习系列-类与结构的区别

2019-11-17 02:58:51
字体:
来源:转载
供稿:网友

C#学习系列-类与结构的区别

参考:http://www.microsoftvirtualacademy.com/Content/ViewContent.aspx?et=9851&m=9830&ct=31038

如有问题,欢迎指正

类:引用类型,存储在堆中,栈中存储引用地址,在方法的传输中只是传输地址的引用,修改指向的对象会影响原有对象的值,传输中消耗内存小。

结构:值类型,存储在堆栈中,传输过程中传输整个对象的副本,修改指向对象的值不会影响原有的对象,传输中消耗内存大。

下面贴代码

    class PRogram    {        static void Main(string[] args)        {            /*声明类对象 并赋值10*/            TestClass TC1 = new TestClass();            TC1.x = 10;            TC1.y = "10";            Console.WriteLine("/*声明类对象TC1 并赋值10*/");            Console.WriteLine("TC1 x={0} y={0}", TC1.x, TC1.y);            TC1.x = 20;            TC1.y = "20";            Console.WriteLine("/*修改类对象 TC1 值为20*/");            Console.WriteLine("TC1 x={0} y={0}", TC1.x, TC1.y);            /*执行类传递 并修改传递后的值*/            Console.WriteLine("/*创建类对象 TC2 指向 TC1,并修改 值为10*/");            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("/*声明结构对象TS1 并赋值10*/");            TestStruct TS1 = new TestStruct();            TS1.x = 10;            TS1.y = "10";            Console.WriteLine("TS1 x={0} y={0}", TS1.x, TS1.y);            Console.WriteLine("/*修改结构对象 TS1 值为20*/");            TS1.x = 20;            TS1.y = "20";            Console.WriteLine("TS1 x={0} y={0}", TS1.x, TS1.y);            /*执行结构传递 并修改传递后的值*/            Console.WriteLine("/*创建结构对象 TS2 指向 TS1,并修改 值为10*/");            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;    }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表