.NET中的结构和类有什么区别?
当前回答
结构是实际值-它们可以为空,但不能为空
这是正确的,但是也要注意,从.NET2开始,结构支持Nullable版本,C#提供了一些语法糖,使其更易于使用。
int? value = null;
value = 1;
其他回答
首先,结构是通过值而不是引用传递的。结构适用于相对简单的数据结构,而类通过多态性和继承从体系结构的角度来看具有更大的灵活性。
其他人可能会比我给你更多的细节,但当我所追求的结构很简单时,我会使用结构。
除了其他答案中描述的所有差异外:
结构不能具有显式无参数构造函数,而类可以结构不能有析构函数,而类可以结构不能从其他结构或类继承,而类可以从其他类继承。(结构和类都可以从接口实现。)
如果您正在观看一段视频,解释所有的差异,您可以查看第29部分-C#教程-C#中类和结构之间的差异。
结构和类别之间的差异:
结构是值类型,而类是引用类型。结构存储在堆栈上,而类存储在堆值类型将其值保存在声明它们的内存中,但引用类型保存对内存中对象的引用。值类型在作用域丢失后立即销毁,而引用类型仅在作用域丢失后销毁变量。该对象随后被垃圾收集器销毁。将结构复制到另一个结构时,该结构的新副本创建。修改的结构不会影响其他结构。将一个类复制到另一个类时,它只复制参考变量。两个引用变量都指向堆上的同一对象。对一个变量所做的更改将影响另一个参考变量。结构不能有析构函数,但类可以有析构器。结构不能具有显式无参数构造函数,而类可以。结构不支持继承,但类支持支持从接口继承。结构为密封型。
Struct | Class | |
---|---|---|
Type | Value-type | Reference-type |
Where | On stack / Inline in containing type | On Heap |
Deallocation | Stack unwinds / containing type gets deallocated | Garbage Collected |
Arrays | Inline, elements are the actual instances of the value type | Out of line, elements are just references to instances of the reference type residing on the heap |
Al-Del Cost | Cheap allocation-deallocation | Expensive allocation-deallocation |
Memory usage | Boxed when cast to a reference type or one of the interfaces they implement, Unboxed when cast back to value type (Negative impact because boxes are objects that are allocated on the heap and are garbage-collected) |
No boxing-unboxing |
Assignments | Copy entire data | Copy the reference |
Change to an instance | Does not affect any of its copies | Affect all references pointing to the instance |
Mutability | Should be immutable | Mutable |
Population | In some situations | Majority of types in a framework should be classes |
Lifetime | Short-lived | Long-lived |
Destructor | Cannot have | Can have |
Inheritance | Only from an interface | Full support |
Polymorphism | No | Yes |
Sealed | Yes | When have sealed keyword (C#), or Sealed attribute (F#) |
Constructor | Can not have explicit parameterless constructors | Any constructor |
Null-assignments | When marked with nullable question mark | Yes (When marked with nullable question mark in C# 8+ and F# 5+ 1) |
Abstract | No | When have abstract keyword (C#), or AbstractClass attribute (F#) |
Member Access Modifiers | public , private , internal |
public , protected , internal , protected internal , private protected |
1不鼓励在F#中使用null,请改用Option类型。
类的实例存储在托管堆上。“包含”实例的所有变量都只是对堆上实例的引用。将对象传递给方法会导致传递引用的副本,而不是对象本身。
结构(从技术上讲,值类型)存储在使用它们的任何地方,很像原始类型。运行时可以随时复制内容,而无需调用自定义的复制构造函数。将值类型传递给方法涉及复制整个值,同样无需调用任何自定义代码。
C++/CLI名称使这种区别更加明显:“ref class”是第一个类,“value class”是第二个类。C#使用的关键字“class”和“struct”只是必须学习的东西。