.NET中的结构和类有什么区别?
当前回答
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类型。
其他回答
结构是实际值-它们可以为空,但不能为空
这是正确的,但是也要注意,从.NET2开始,结构支持Nullable版本,C#提供了一些语法糖,使其更易于使用。
int? value = null;
value = 1;
如前所述:类是引用类型,而结构是具有所有后果的值类型。
根据经验,框架设计指南建议在以下情况下使用结构而不是类:
它的实例大小小于16字节它逻辑上表示单个值,类似于原始类型(int、double等)它是不可变的它不必经常装箱
首先,结构是通过值而不是引用传递的。结构适用于相对简单的数据结构,而类通过多态性和继承从体系结构的角度来看具有更大的灵活性。
其他人可能会比我给你更多的细节,但当我所追求的结构很简单时,我会使用结构。
除了其他答案中描述的所有差异外:
结构不能具有显式无参数构造函数,而类可以结构不能有析构函数,而类可以结构不能从其他结构或类继承,而类可以从其他类继承。(结构和类都可以从接口实现。)
如果您正在观看一段视频,解释所有的差异,您可以查看第29部分-C#教程-C#中类和结构之间的差异。
每个项目的简短摘要:
仅限班级:
可以支持继承是引用(指针)类型引用不能为空每个新实例的内存开销
仅结构:
无法支持继承是值类型按值传递(如整数)不能有空引用(除非使用了Nullable)每个新实例没有内存开销-除非“装箱”
类和结构:
复合数据类型通常用于包含一些具有某种逻辑关系的变量吗可以包含方法和事件可以支持接口
推荐文章
- HTTP POST返回错误:417“期望失败。”
- 为什么Path。以Path.DirectorySeparatorChar开头的文件名合并不正确?
- c# .NET中的App.config是什么?如何使用它?
- String类中的什么方法只返回前N个字符?
- 我如何提高ASP。NET MVC应用程序性能?
- 无法解析类型为“Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务
- 如何在没有任何错误或警告的情况下找到构建失败的原因
- Visual Studio弹出提示:“操作无法完成”
- 否ConcurrentList<T>在。net 4.0?
- 在c#中解析字符串为日期时间
- 由Jon Skeet撰写的《Singleton》澄清
- 自定义数字格式字符串始终显示符号
- Post参数始终为空
- string.ToLower()和string.ToLowerInvariant()
- 检查instance是否属于某个类型