何时在 C# 中使用 struct 而不是 class:理解值类型和引用类型
大家好!我写 C# 大约一年了,一直有个问题困扰着我:什么时候该用 struct,什么时候该用 class?我似乎明白区别——struct 是值类型,而 class 是引用类型。但在实践中,我经常感到困惑。
例如,我有这样的代码:
```csharp
public class PointClass
{
public int X { get; set; }
public int Y { get; set; }
public PointClass(int x, int y) { X = x; Y = y; }
}
public struct PointStruct
{
public int X { get; set; }
public int Y { get; set; }
public PointStruct(int x, int y) { X = x; Y = y; }
}
```
看起来两者做的是同一件事。但我读到过,对于小对象,struct 更快,因为它们存储在栈上,而 class 存储在堆上。另一方面,我听说 struct 不应该与 collections、LINQ 或 async 一起使用,因为它们会开始被到处复制,导致性能下降。
另外,我不明白为什么在 struct 中不能声明无参构造函数(