简体   繁体   English

为什么我们需要结构? (C#)

[英]Why do we need struct? (C#)

To use a struct, we need to instantiate the struct and use it just like a class. 要使用结构,我们需要实例化结构并像使用类一样使用它。 Then why don't we just create a class in the first place? 那为什么我们不首先创建一个类?

struct是一个值类型,所以如果你创建一个副本,它实际上会物理复制数据,而对于一个类,它只会复制对数据的引用

A major difference between the semantics of class and struct is that struct s have value semantics. classstruct语义之间的主要区别在于struct具有值语义。 What is this means is that if you have two variables of the same type, they each have their own copy of the data. 这意味着如果你有两个相同类型的变量,它们每个都有自己的数据副本。 Thus if a variable of a given value type is set equal to another (of the same type), operations on one will not affect the other (that is, assignment of value types creates a copy). 因此,如果给定值类型的变量设置为等于另一个(相同类型),则对一个的操作不会影响另一个(即,值类型的赋值会创建副本)。 This is in sharp contrast to reference types. 这与参考类型形成鲜明对比。

There are other differences: 还有其他差异:

  1. Value types are implicitly sealed (it is not possible to derive from a value type). 值类型是隐式sealed (不可能从值类型派生)。
  2. Value types can not be null . 值类型不能为null
  3. Value types are given a default constructor that initialzes the value type to its default value. 值类型被赋予一个默认构造函数,将值类型初始化为其默认值。
  4. A variable of a value type is always a value of that type. 值类型的变量始终是该类型的值。 Contrast this with classes where a variable of type A could refer to a instance of type B if B derives from A . 将此与类型进行对比,其中类型A的变量可以引用类型B的实例,如果B派生自A

Because of the difference in semantics, it is inappropriate to refer to struct s as "lightweight classes." 由于语义的不同,将struct称为“轻量级类”是不合适的。

In C#, a struct is a value type, unlike classes which are reference types. 在C#中,struct是一种值类型,与引用类型的类不同。 This leads to a huge difference in how they are handled, or how they are expected to be used. 这导致它们的处理方式或预期如何使用它们的巨大差异。

You should probably read up on structs from a book. 你应该读一本书中的结构。 Structs in C# aren't close cousins of class like in C++ or Java. C#中的结构不像C ++或Java那样是类的近亲。

All of the reasons I see in other answers are interesting and can be useful, but if you want to read about why they are required (at least by the VM) and why it was a mistake for the JVM to not support them (user-defined value types), read Demystifying Magic: High-level Low-level Programming . 我在其他答案中看到的所有原因都很有趣并且很有用,但是如果你想了解它们为什么是必需的 (至少是VM)以及为什么JVM不支持它们是错误的(用户 -定义的值类型),阅读Demystifying Magic:高级低级编程 As it stands, C# shines in talking about the potential to bring safe, managed code to systems programming. 就目前而言,C#在谈论将安全的托管代码引入系统编程的潜力时会熠熠生辉。 This is also one of the reasons I think the CLI is a superior platform [than the JVM] for mobile computing. 这也是我认为CLI是移动计算的优越平台[比JVM]的原因之一。 A few other reasons are listed in the linked paper. 链接文件中列出了其他一些原因。

It's important to note that you'll very rarely, if ever, see an observable performance improvement from using a struct. 重要的是要注意,如果有的话,你很少会看到使用结构时可观察到的性能提升。 The garbage collector is extremely fast, and in many cases will actually outperform the structs. 垃圾收集器非常快,在许多情况下实际上会超过结构。 When you add in the nuances of them, they're certainly not a first-choice tool. 当你添加它们的细微差别时,它们肯定不是首选工具。 However, when you do need them and have profiler results or system-level constructs to prove it, they get the job done. 但是,当您确实需要它们并具有探查器结果或系统级构造来证明它时,他们就可以完成工作。

Edit: If you wanted an answer of why we need them as opposed to what they do, ^^^ 编辑:如果你想要回答为什么我们需要它们而不是他们做什么,^^^

This is a myth that struct are always created on heap. 这是一个总是在堆上创建struct的神话。 Ok it is right that struct is value type and class is reference type. 好的是,struct是值类型,类是引用类型。 But remember that 但请记住

1. A Reference Type always goes on the Heap. 1.参考类型总是在堆上。
2. Value Types go where they were declared. 2.值类型转到声明它们的位置。

Now what that second line means is I will explain with below example 现在第二行意味着什么,我将用下面的例子来解释

Consider the following method 考虑以下方法

  public void DoCalulation()
  {
        int num;
        num=2; 
  }

Here num is a local variable so it will be created on stack . 这里num是一个局部变量,因此它将在堆栈上创建。

Now consider the below example 现在考虑下面的例子

public class TestClass
{          
    public int num;
}
public void DoCalulation()
{
    TestClass myTestClass = new TestClass ();
    myTestClass.num=2;
}

This time num is the num is created on heap.Ya in some cases value types perform more than reference types as they don't require garbage collection. 这个时间num是在堆上创建的num.Ya在某些情况下,值类型执行的不仅仅是引用类型,因为它们不需要垃圾回收。

Also remeber: 还记得:

The value of a value type is always a value of that type. 值类型的值始终是该类型的值。 The value of a reference type is always a reference. 引用类型的值始终是引用。

And you have to think over the issue that if you expect that there will lot be instantiation then that means more heap space yow will deal with ,and more is the work of garbage collector.For that case you can choose structs. 你必须考虑这个问题,如果你期望有很多实例化,那么这意味着更多的堆空间将会处理,更多的是垃圾收集器的工作。对于这种情况,你可以选择结构。

the difference is that a struct is a value-type I've found them useful in 2 situations 不同之处在于结构是一种值类型,我发现它们在两种情况下很有用

1) Interop - you can specify the memory layout of a struct, so you can guarantee that when you invoke an unmanaged call. 1)Interop - 您可以指定结构的内存布局,因此您可以保证在调用非托管调用时。

2) Performance - in some (very limited) cases, structs can be faster than classes, In general, this requires structs to be small (I've heard 16 bytes or less) , and not be changed often. 2)性能 - 在一些(非常有限的)情况下,结构可能比类快,一般来说,这需要结构很小(我听到16字节或更少),并且不经常更改。

One of the main reasons is that, when used as local variables during a method call, structs are allocated on the stack. 其中一个主要原因是,在方法调用期间用作局部变量时,将在堆栈上分配结构。

Stack allocation is cheap, but the big difference is that de-allocation is also very cheap. 堆栈分配很便宜,但最大的区别是解除分配也很便宜。 In this situation, the garbage collector doesn't have to track structs -- they're removed when returning from the method that allocated them when the stack frame is popped. 在这种情况下,垃圾收集器不必跟踪结构 - 当从弹出堆栈帧时分配它们的方法返回时,它们被删除。

  • edit - clarified my post re: Jon Skeet's comment. 编辑 - 澄清了我的帖子:Jon Skeet的评论。

Structs have many different semantics to classes. 结构对类有许多不同的语义。 The differences are many but the primary reasons for their existence are: 差异很大,但存在的主要原因是:

  1. They can be explicitly layed out in memmory 它们可以在memmory中明确地列出
    • this allows certain interop scenarios 这允许某些互操作场景
  2. They may be allocated on the stack 它们可以在堆栈上分配
    • Making some sorts of high performance code possible in a much simpler fashion 以更简单的方式制作某些高性能代码

A struct is a value type (like Int32), whereas a class is a reference type. 结构是值类型(如Int32),而类是引用类型。 Structs get created on the stack rather than the heap. 结构是在堆栈而不是堆上创建的。 Also, when a struct is passed to a method, a copy of the struct is passed, but when a class instance is passed, a reference is passed. 此外,当结构传递给方法时,会传递结构的副本,但是当传递类实例时,会传递引用。

If you need to create your own datatype, say, then a struct is often a better choice than a class as you can use it just like the built-in value types in the .NET framework. 如果您需要创建自己的数据类型,那么结构通常是比类更好的选择,因为您可以像使用.NET框架中的内置值类型一样使用它。 There some good struct examples you can read here . 你可以在这里阅读一些很好的结构示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM