C# – Record, Class, Struct
作者:互联网
前言
之前在 C# – 10.0 已经有介绍过 Record 了. 但之前还没怎么用到, 最近有用到了, 所以特别写多一篇.
Class vs Struct
它们最大的区别在于 Class 是引用类型, Struct 是值类型. 引用类型 (heap) vs 值类型 (stack)
定义是差不多的, 可以有 property, method, constructor 等等
public struct DimensionStruct { public int Width { get; set; } public int Height { get; set; } } public class DimensionClass { public int Width { get; set; } public int Height { get; set; } }
在对比值和引用的时候就看区别了
var dimensionClass = new DimensionClass { Width = 100, Height = 100 }; var dimensionClass2 = dimensionClass; var d = Object.ReferenceEquals(dimensionClass, dimensionClass2); // true var e = Object.Equals(dimensionClass, dimensionClass2); // true var f = Object.Equals(dimensionClass, new DimensionClass { Width = 100, Height = 100 }); // false 虽然里面 value 一样
实例指向同一个地址, Object.Equals 对比的是它们的地址是否一致, 而不是值是否一致.
在看 Struct
var dimensionStruct = new DimensionStruct { Width = 100, Height = 100 }; var dimensionStruct2 = dimensionStruct; var a = Object.ReferenceEquals(dimensionStruct, dimensionStruct2); // false var b = Object.Equals(dimensionStruct, dimensionStruct2); // true var c = Object.Equals(dimensionStruct, new DimensionStruct { Width = 100, Height = 100 }); // true 值一样就行了
地址肯定是不一样的了. Object.Equals 对比的是里面的值. 值一样就行了.
When to use Struct?
我个人是没有特别感觉什么情况非用 Struct 不可.
比较常见的是 Size (width, height), Coordinate (x, y) 这类的 object value 就会用 struct.
Record
参考:
Intro to Records in C# 9 - How To Use Records And When To Use Them
Record 是 9.0 出来的.
标签:Width,C#,Object,public,Record,var,100,Class 来源: https://www.cnblogs.com/keatkeat/p/16513491.html