C#中的值类型和引用类型有什么区别? [英] What are the differences between value types and reference types in C#?

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

问题描述

我知道一些不同之处,

  1. 值类型存储在堆栈中,而引用类型存储在托管堆中.
  2. 值类型变量直接包含它们的值,而引用变量只包含对在托管堆上创建的对象位置的引用.

我错过了其他任何区别吗...如果有,它们是什么?

Is there any other difference i missed... If so,what are they?

推荐答案

请阅读:堆栈是一个实现细节,并且不要再重复这个谣言,即堆栈分配是将值类型与引用类型区分开来的原因.网.CLR 可以选择将变量分配到任何它想要的位置.

Please read: The stack is an implementation detail, and don't ever again repeat the canard that stack allocation is what differentiates value types from reference types in .NET. The CLR may choose to allocate a variable anywhere it wants to.

最重要的区别在于赋值语义.当您将值类型分配给变量(或将其作为参数传递给方法)时,所有数据都会被复制.分配引用类型时,只会复制一个引用 - 两个引用都指向内存中的同一个对象实例.

The most important difference is in the assignment semantics. When you assign a value type to a variable (or pass it to a method as an argument), all of the data is copied. When you assign a reference type, only a reference is copied - both references point to the same object instance in memory.

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

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