在C#中,使用值类型与引用类型 [英] In C#, use of value types vs. reference types

查看:197
本文介绍了在C#中,使用值类型与引用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是:

  • 何时应使用值类型以及何时应使用引用类型?
  • 一个人相对于另一个人的优点和缺点是什么?
  • 如果人们到处都使用引用类型怎么办?有什么害处吗?

还请讨论每个优点和缺点.我也想了解这一点.

Please also discuss advantages and disadvantages of each one. I want to understand that as well.

推荐答案

对此似乎有很多困惑,乔恩·斯凯特(Jon Skeet)在他的著作"C#In Depth,2nd Ed."中做了很好的清理工作. " (第2.3节).

There seems to be a lot of confusion over this, and Jon Skeet does a good job of clearing it up in his book "C# In Depth, 2nd Ed." (section 2.3).

我个人的方法(可能正确也可能不正确)是仅使用结构/枚举(值类型)来表示轻量级的原子数据结构,我知道我将经常在某种逻辑或数学运算中使用该结构-想想Point

My personal approach, which may or may not be right, is to ONLY use structs/enumerations (value types) to represent lightweight, atomic data structures that I know I'll be using frequently in some kind of logical or mathematical operations - think Point, etc.

这样,我认为我可以避免垃圾收集性能下降.但是,乔恩(Jon)在他的书中指出,并没有真正的保证,特别是在新版本的运行时中,是否有任何东西会进入堆栈.

That way I figure I can avoid the garbage collection performance penalty. However, Jon points out in that section of his book that there's no real guarantee, especially in new versions of the runtime, whether something will go on the stack at all.

所以我最好的答案是谨慎使用诸如struct之类的东西,并且要非常清楚为什么要使用它们.提防过早的优化.如果您能拿到一份副本,请阅读乔恩书中的那部分内容,因为他在阐明整个主题方面做得很好.

So my best answer is use things like structs sparingly and be very conscious about why you're using them if you do. Watch out for premature optimization. And read that section in Jon's book if you can get your hands on a copy, because he does a good job of clarifying this whole topic.

相关:何时使用struct?

这篇关于在C#中,使用值类型与引用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆