什么是结构和类在.NET之间的区别是什么? [英] What's the difference between struct and class in .NET?

查看:193
本文介绍了什么是结构和类在.NET之间的区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是结构和类在.NET之间的区别是什么?

What's the difference between struct and class in .NET?

我在寻找一个清晰,简明,准确的答案。理想的情况是作为实际的答案,虽然联系好解释是欢迎的。

I'm looking for a clear, concise and accurate answer. Ideally as the actual answer, although links to good explanations are welcome.

推荐答案

在.NET中,有两种类型的类型的引用类型值类型的。

In .NET, there are two categories of types, reference types and value types.

结构是值类型的和类的引用类型的。

一般不同的是,引用类型的住在堆和值类型的住行内,也就是说,无论它是你的变量或字段的定义。

The general difference is that a reference type lives on the heap, and a value type lives inline, that is, wherever it is your variable or field is defined.

一个包含的值类型变量的包含了整个的值类型的值。对于一个结构,这意味着该变量包含整个结构,其所有的领域。

A variable containing a value type contains the entire value type value. For a struct, that means that the variable contains the entire struct, with all its fields.

一个包含的引用类型变量的包含一个指向,或引用的到别的在内存的某个地方的实际价值所在。

A variable containing a reference type contains a pointer, or a reference to somewhere else in memory where the actual value resides.

这有一个好处,首先:

  • 值类型的总是包含一个值
  • 引用类型的可包含的的-reference,这意味着它们不引用任何东西的那一刻
  • value types always contains a value
  • reference types can contain a null-reference, meaning that they don't refer to anything at all at the moment

在内部,引用类型的s的,还有其他的行为模式,实现为指针,知道,知道如何变量赋值作品:

Internally, reference types are implemented as pointers, and knowing that, and knowing how variable assignment works, there are other behavioral patterns:

  • 复制的值类型的内容的变量到另一个变量,复制全部内容复制到新的变量,使得两个不同。换句话说,在复制后,改变一个不会影响其他
  • 复制的引用类型的内容的变量到另一个变量,复制基准,这意味着你现在有两个引用到相同的别的地方的存储的实际数据。换句话说,拷贝后,改变一个参考的数据会影响到其他的为好,但仅仅是因为你真的只是在看相同的数据这两个地方
  • copying the contents of a value type variable into another variable, copies the entire contents into the new variable, making the two distinct. In other words, after the copy, changes to one won't affect the other
  • copying the contents of a reference type variable into another variable, copies the reference, which means you now have two references to the same somewhere else storage of the actual data. In other words, after the copy, changing the data in one reference will appear to affect the other as well, but only because you're really just looking at the same data both places

在声明变量或字段,下面是两种类型不同:

When you declare variables or fields, here's how the two types differ:

  • 变量:值类型的生活在栈中,引用类型的生活的堆栈指针的地方堆内存在实际存储生命
  • 类/结构字段:值类型的居住类内部,引用类型的生活类的指针内部某处堆内存,其中内存的实际生活。
  • variable: value type lives on the stack, reference type lives on the stack as a pointer to somewhere in heap memory where the actual memory lives
  • class/struct-field: value type lives inside the class, reference type lives inside the class as a pointer to somewhere in heap memory where the actual memory lives.

这篇关于什么是结构和类在.NET之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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