最新文章 (全部类别)
LinERP - 线联ERP - 状态栏操作说明
LinERP - 线联ERP - 工具栏按钮列表
LinERP - 线联ERP - 表格列头通用弹出菜单
LinERP - 线联ERP - 物料管理
CMS修改主菜单类别编码CategoryNo
LinERP - 线联ERP试用版下载
LinERP - 线联ERP客户服务
LinERP - 线联ERP主界面
LinERP - 线联ERP系统登陆
LinERP - 线联ERP简介
明细表支持批量操作删除
C# 图片按钮特效:鼠标移入变浅,移出恢复原样 (ImageButtonHover类)
C# 复制对象属性 CopyProperties扩展方法
线联ERP - 海康威视人脸考勤机设置固定IP、重启设备操作手册
线联ERP - 用户操作手册 - 系统初始化
线联ERP - 什么是主账套?
线联ERP - 用户操作手册 - 公司资料设置
C/S快速开发框架旗舰版CSFrameworkV6.0 - VS开发环境配置
修复BUG: CSFramework.EF框架 Remove<T>, RemoveWhere<T>
使用Xlight FTP文件服务器
印章公章在线免费制作
CSFrameworkV6.1旗舰版 - appsettings.json 配置文件增加参数
推荐:使用Photoshop制作ico图标
C#.NET格式化显示:数字末尾不显示0
SQL脚本:更新主表的完成标记FlagFinish=Y
FastReport.NET 设计器汉化&运行时汉化
VS2026/VS2022 关闭 “自动添加 using 命名空间”
C#将List<T>导出为 CSV 文件(Excel 直接打开,无需第三方组件包)
.NET8+EF.Core开发的大型ERP系统客户端4GB电脑测试报告
线联ERP - LinERP HR+考勤系统正式上线
CSFrameworkV6旗舰版 - 复制单据功能
QMS软件简介 | 成本核算报价系统软件简介
QMS - 五金制品行业成本核算报价系统 - 货币资料
QMS - 五金制品行业成本核算报价系统 - 公共字典管理
QMS - 五金制品行业成本核算报价系统 - 物料类别
QMS - 五金制品行业成本核算报价系统 - 物料管理
QMS - 五金制品行业成本核算报价系统 - 图纸文件管理
QMS - 五金制品行业成本核算报价系统 - 供应商管理
QMS - 五金制品行业成本核算报价系统 - 车型费管理
QMS - 五金制品行业成本核算报价系统 - 制程段配置
QMS - 五金制品行业成本核算报价系统 - 产品咨询
QMS五金制品行业报价系统 - 用户操作手册 - 成本中心核算
QMS五金制品行业报价系统 - 用户操作手册 - 报价单 - Quotation
QMS五金制品行业报价系统 - 用户操作手册 - 成本汇总表
QMS五金制品行业报价系统 - 用户操作手册 - 采购评估
QMS五金制品行业报价系统 - 用户操作手册 - 成本基础资料表
QMS五金制品行业报价系统 - 用户操作手册 - 新品可行性评估
QMS - 成本核算报价管理系统软件截图
QMS五金制品行业报价系统 - 用户操作手册 - 业务员管理
QMS五金制品行业报价系统 - 用户操作手册 - 客户管理
.net敏捷开发,创造卓越

C#.Net对象内存模型及堆/栈数据结构详解 (三)


C#.Net对象内存模型及堆/栈数据结构详解 (三)

C# Heap(ing) Vs Stack(ing) in .NET: Part III
本文转载http://www.c-sharpcorner.com

Even though with the .NET framework we don''t have to actively worry about memory management and garbage collection (GC), we still have to keep memory management and GC in mind in order to optimize the performance of our applications. Also, having a basic understanding of how memory management works will help explain the behavior of the variables we work with in every program we write. In this article we''ll cover an issue that arises from having reference variables in the heap and how to fix it using ICloneable.

A Copy Is Not A Copy.

To clearly define the problem, let''s examine what happens when there is a value type on the heap versus having a reference type on the heap. First we''ll look at the value type. Take the following class and struct. We have a Dude class which contains a Name element and two Shoe(s). We have a CopyDude() method to make it easier to make new Dudes.

           public struct Shoe{

               public string Color;

           }

 

           public class Dude

           {

                public string Name;

                public Shoe RightShoe;

                public Shoe LeftShoe;

 

                public Dude CopyDude()

                {

                    Dude newPerson = new Dude();

                     newPerson.Name = Name;

                     newPerson.LeftShoe = LeftShoe;

                     newPerson.RightShoe = RightShoe;

 

                     return newPerson;

                }

 

                public override string ToString()

                {

                     return (Name + " : Dude!, I have a " + RightShoe.Color  +

                         " shoe on my right foot, and a " +

                          LeftShoe.Color + " on my left foot.");

                }

 

           }

Our Dude class is a variable type and because the Shoe struct is a member element of the class they both end up on the heap.

 

When we run the following method:

           public static void Main()

           {

               Class1 pgm = new Class1();

 

                  Dude Bill = new Dude();

                  Bill.Name = "Bill";

                  Bill.LeftShoe = new Shoe();

                  Bill.RightShoe = new Shoe();

                  Bill.LeftShoe.Color = Bill.RightShoe.Color = "Blue";

 

                  Dude Ted =  Bill.CopyDude();

                  Ted.Name = "Ted";

                  Ted.LeftShoe.Color = Ted.RightShoe.Color = "Red";

 

                  Console.WriteLine(Bill.ToString());

                  Console.WriteLine(Ted.ToString());            

 

           }

We get the expected output:

Bill : Dude!, I have a Blue shoe on my right foot, and a Blue on my left foot.
Ted : Dude!, I have a Red shoe on my right foot, and a Red on my left foot.

What happens if we make the Shoe a reference type?  Herein lies the problem. If we change the Shoe to a reference type as follows:

           public class Shoe{

               public string Color;

           }

and run the exact same code in Main(), look how our input changes:

Bill : Dude!, I have a Red shoe on my right foot, and a Red on my left foot
Ted : Dude!, I have a Red shoe on my right foot, and a Red on my left foot

The Red shoe is on the other foot. This is clearly an error. Do you see why it''s happening? Here''s what we end up with in the heap.

 

Because we now are using Shoe as a reference type instead of a value type and when the contents of a reference type are copied only the pointer is copied (not the actual object being pointed to), we have to do some extra work to make our Shoe reference type behave more like a value type.

Luckily, we have an interface that will help us out: ICloneable. This interface is basically a contract that all Dudes will agree to and defines how a reference type is duplicated in order to avoid our "shoe sharing" error. All of our classes that need to be "cloned" should use the ICloneable interface, including the Shoe class.

ICloneable consists of one method: Clone()

                  public object Clone()

                  {

 

                  }

Here''s how we''ll implement it in the Shoe class:

           public class Shoe : ICloneable

             {

                  public string Color;

                  #region ICloneable Members

 

                  public object Clone()

                  {

                      Shoe newShoe = new Shoe();

                      newShoe.Color = Color.Clone() as string;

                      return newShoe;

                  }

 

                  #endregion

             }

Inside the Cone() method, we just make a new Shoe, clone all the reference types and copy all the value types and return the new object. You probably noticed that the string class already implements ICloneable so we can call Color.Clone(). Because Clone() returns a reference to an object, we have to "retype" the reference before we can set the Color of the shoe.

Next, in our CopyDude() method we need to clone the shoes instead of copying them

                public Dude CopyDude()

                {

                    Dude newPerson = new Dude();

                     newPerson.Name = Name;

                     newPerson.LeftShoe = LeftShoe.Clone() as Shoe;

                     newPerson.RightShoe = RightShoe.Clone() as Shoe;

 

                     return newPerson;

                }

Now, when we run main:

           public static void Main()

           {

               Class1 pgm = new Class1();

 

                  Dude Bill = new Dude();

                  Bill.Name = "Bill";

                  Bill.LeftShoe = new Shoe();

                  Bill.RightShoe = new Shoe();

                  Bill.LeftShoe.Color = Bill.RightShoe.Color = "Blue";

 

                  Dude Ted =  Bill.CopyDude();

                  Ted.Name = "Ted";

                  Ted.LeftShoe.Color = Ted.RightShoe.Color = "Red";

 

                  Console.WriteLine(Bill.ToString());

                  Console.WriteLine(Ted.ToString());            

 

           }

We get:

Bill : Dude!, I have a Blue shoe on my right foot, and a Blue on my left foot
Ted : Dude!, I have a Red shoe on my right foot, and a Red on my left foot

Which is what we want.

 

Wrapping Things Up.

So as a general practice, we want to always clone reference types and copy value types. (It will reduce the amount of aspirin you will have to purchase to manage the headaches you get debugging these kinds of errors.)

So in the spirit of headache reduction, let''s take it one step further and clean up the Dude class to implement ICloneable instead of using the CopyDude() method.

           public class Dude: ICloneable

           {

                public string Name;

                public Shoe RightShoe;

                public Shoe LeftShoe;

 

                public override string ToString()

                {

                     return (Name + " : Dude!, I have a " + RightShoe.Color  +

                         " shoe on my right foot, and a " +

                          LeftShoe.Color + " on my left foot.");

                    }

                  #region ICloneable Members

 

                  public object Clone()

                  {

                       Dude newPerson = new Dude();

                       newPerson.Name = Name.Clone() as string;

                       newPerson.LeftShoe = LeftShoe.Clone() as Shoe;

                       newPerson.RightShoe = RightShoe.Clone() as Shoe;

 

                       return newPerson;

                  }

 

                  #endregion

             }

And we''ll change the Main() method to use Dude.Clone()

           public static void Main()

           {

               Class1 pgm = new Class1();

 

                  Dude Bill = new Dude();

                  Bill.Name = "Bill";

                  Bill.LeftShoe = new Shoe();

                  Bill.RightShoe = new Shoe();

                  Bill.LeftShoe.Color = Bill.RightShoe.Color = "Blue";

 

                  Dude Ted =  Bill.Clone() as Dude;

                  Ted.Name = "Ted";

                  Ted.LeftShoe.Color = Ted.RightShoe.Color = "Red";

 

                  Console.WriteLine(Bill.ToString());

                  Console.WriteLine(Ted.ToString());            

 

           }

And our final output is:

Bill : Dude!, I have a Blue shoe on my right foot, and a Blue on my left foot.
Ted : Dude!, I have a Red shoe on my right foot, and a Red on my left foot.

So all is well.

Something interesting to note is that the assignment operator (the "=" sign) for the System.String class actually clones the string so you don''t have to worry about duplicate references. However you do have to watch our for memory bloating. If you look back at the diagrams, because the string is a reference type it really should be a pointer to another object in the heap, but for simplicity''s sake, it''s shown as a value type.

In Conclusion.

As a general practice, if we plan on ever copying of our objects, we should implement (and use) ICloneable.  This enables our reference types to somewhat mimic the behavior of a value type. As you can see, it is very important to keep track of what type of variable we are dealing with because of differences in how the memory is allocated for value types and reference types.

In the next article, we''ll look at a way to reduce our code "footprint" in memory.



本文来源:
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
C/S框架网
上一篇:C#.Net对象内存模型及堆/栈数据结构详解 (二)
下一篇:C#.Net对象内存模型及堆/栈数据结构详解 (四)
评论列表

发表评论

评论内容
昵称:
关联文章

C#.Net对象内存模型/数据结构详解 ()
C#.Net对象内存模型/数据结构详解 (一)
C#.Net对象内存模型/数据结构详解 (二)
C#.Net对象内存模型/数据结构详解 (四)
DbFramework数据库实体类对象模型框架( 支持MsSQL,MySQL,Oracle种数据库)
Asp.Net层体系结构应用实例(附C#源代码)
CSFramework对象模型框架(DbDataUpdate),支持MsSQL,MySQL,Oracle种数据库操作
CSFramework代码生成器生成种ORM模型类(静态类ORM,实体类ORM,标准对象
C#.NET GC.Collect垃圾回收机制详解
CSFramework代码生成器根据数据库表结构生成实体对象模型C#代码)
C#.Net WCF实例详解源码下载
Winform层架构教程,CS层结构图源码实例讲解
DbDataUpdate - 自动提交对象模型数据 - 常用数据类型测试
[原创] Asp.Net层体系结构应用实例(2)源代码
CSFramework.WebApi用户请求对象模型
基于Winform层架构+WCF+ORM模型的快速开发框架
了解溢出StackOverFloweExeption的原理吗?
C#.Net窗体多重继承构造器Load事件执行顺序详解
C#数据转换类ConvertEx,封装.Net的Convert对象
C#.NET 实体框架EF(Entity Framework)详解

热门标签
软件著作权登记证书 .NET .NET Reactor .NET5 .NET6 .NET7 .NET8 .NET9 .NETFramework AI编程 APP AspNetCore AuthV3 Auth-软件授权注册系统 Axios B/S B/S开发框架 B/S框架 BSFramework Bug Bug记录 C#加密解密 C#源码 C/S CHATGPT CMS系统 CodeGenerator CSFramework.DB CSFramework.EF CSFramework.License CSFrameworkV1学习版 CSFrameworkV2标准版 CSFrameworkV3高级版 CSFrameworkV4企业版 CSFrameworkV5旗舰版 CSFrameworkV6.0 CSFrameworkV6.1 CSFrameworkV6旗舰版 DAL数据访问层 DaMeng Database datalock DbFramework DeepSeek Demo教学 Demo实例 Demo下载 DevExpress教程 Docker Desktop DOM ECS服务器 EFCore EF框架 Element-UI EntityFramework ERP ES6 Excel FastReport GIT HR HR考勤系统 IDatabase IIS JavaScript LinERP LINQ MES MiniFramework MIS MSSQL MySql NavBarControl NETCore Node.JS NPM OMS Oracle资料 ORM PaaS POS PostgreSql Promise API PSD QMS RedGet Redis RSA SAP Schema SEO SEO文章 SQL SQLConnector SQLite SqlServer Swagger TMS系统 Token令牌 VS2022 VSCode VS升级 VUE WCF WebApi WebApi NETCore WebApi框架 WEB开发框架 Windows服务 Winform 开发框架 Winform 开发平台 WinFramework Workflow工作流 Workflow流程引擎 XtraReport 安装环境 版本区别 报表 备份还原 踩坑日记 操作手册 成本核算系统 达梦数据库 代码生成器 电子线材ERP 迭代开发记录 功能介绍 官方软件下载 国际化 海康威视考勤 基础资料窗体 架构设计 角色权限 开发sce 开发工具 开发技巧 开发教程 开发框架 开发平台 开发指南 客户案例 快速搭站系统 快速开发平台 框架升级 毛衫行业ERP 秘钥 密钥 企业网络维护 权限设计 软件报价 软件测试报告 软件加壳 软件简介 软件开发框架 软件开发平台 软件开发文档 软件授权 软件授权注册系统 软件体系架构 软件下载 软件著作权登记证书 软著证书 三层架构 设计模式 生成代码 实用小技巧 视频下载 收钱音箱 数据锁 数据同步 塑木地板行业ERP 推荐软件 微信小程序 未解决问题 文档下载 喜鹊ERP 喜鹊软件 系统对接 线联ERP 详细设计说明书 新功能 信创 行政区域数据库 需求分析 疑难杂症 蝇量级框架 蝇量框架 用户管理 用户开发手册 用户控件 在线软件 在线支付 纸箱ERP 智能语音收款机 自定义窗体 自定义组件 自动升级程序
联系我们
联系电话:13923396219(微信同号)
电子邮箱:23404761@qq.com
站长微信二维码
微信二维码