Csharp/C#教程:浅析C#中结构与类的区别分享

一、

  结构:值类型,存储在堆栈中,位于计算机的内存逻辑区域中    类  :引用类型,存储在堆中,位于计算机内存的不同逻辑位置

二、

 较小的数据使用结构;  将一个结构值传递到方法时,传递的是整个数据结构;  传递一个类,实际上是将引用传递到对象,即只有内存地址;  对结构修改,改变的是结构的副本,这是值类型工作方式的定义:传递值的副本;  传递一个引用到类本身意味着在类中修改值,实际上改变的是原始对象;

三、代码例子

1.新建PointClass.cs

namespaceStructAndClass { internalclassPointClass { publicPointClass(intx,inty) { X=x; Y=y; } publicintX{get;set;} publicintY{get;set;} } }

2.新建PointStruct.cs

namespaceStructAndClass { internalstructPointStruct { publicintX{get;set;} publicintY{get;set;} publicPointStruct(intx,inty) { X=x; Y=y; } } }

3.Program.cs

usingSystem; namespaceStructAndClass { internalclassProgram { privatestaticvoidMain(string[]args) { Console.WriteLine("PointStruct====="); varpStruct=newPointStruct(10,10); Console.WriteLine("初始值:x={0},y={1}",pStruct.X,pStruct.Y); ModifyPointStruct(pStruct); Console.WriteLine("调用ModifyPointStruct()后的值:x={0},y={1}",pStruct.X,pStruct.Y); Console.WriteLine(); Console.WriteLine("PointClass====="); varpClass=newPointClass(10,10); Console.WriteLine("初始值:x={0},y={1}",pClass.X,pClass.Y); ModifyPointClass(pClass); Console.WriteLine("调用ModifyPointClass()后的值:x={0},y={1}",pClass.X,pClass.Y); Console.Read(); } privatestaticvoidModifyPointStruct(PointStructpoint) { Console.WriteLine("调用方法:ModifyPointStruct"); point.X=20; point.Y=20; Console.WriteLine("修改成的值:x={0},y={1}",point.X,point.Y); } privatestaticvoidModifyPointClass(PointClasspoint) { Console.WriteLine("调用方法:ModifyPointClass"); point.X=20; point.Y=20; Console.WriteLine("修改成的值:x={0},y={1}",point.X,point.Y); } } }

4.结果:

【解析】

ModifyPointStruct(PointStructpoint)调用时修改的只是结构副本,所以原来的结构并没有发生变化;  

ModifyPointClass(PointClasspoint)调用时所修改的对象是原对象,因为参数传递过来的是一个引用地址,这地址指向原对象

四、上述就是C#学习教程:浅析C#中结构与类的区别分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/907184.html

(0)
上一篇 2021年10月24日
下一篇 2021年10月24日

精彩推荐