简体   繁体   English

为什么“ System.Version”是引用类型(类)而不是值类型(结构)?

[英]Why is the 'System.Version' a reference type (class) and not a value type (struct)?

If I look at the members of the .NET type System.Version it might be a better idea to create such a type as value type (C# struct) instead of a reference type (class). 如果我查看.NET类型System.Version的成员,最好创建一个值类型(C#结构)而不是引用类型(类)的类型。

What might be the reasons or arguments that Microsoft decided to implement that type in that way? Microsoft决定以这种方式实现该类型的原因或参数可能是什么? Is it simply a kind of "bug" / mistake / inconsequence or a "feature" (in other words: "really wanted and useful"? 它是一种简单的“错误” /错误/不足之处还是“功能”(换句话说:“真的想要和有用”)?

There are methods like Parse() and TryParse() which are typical for value types, eg System.Int32 , System.Double or System.Guid . 有一些类似Parse()TryParse()的方法 ,这些方法通常用于值类型,例如System.Int32System.DoubleSystem.Guid The properties of System.Version only store short and integer values (s. System.TimeSpan ), the type itself is comparable (with operators) and as struct it might not be necessary to make it cloneable. System.Version的属性仅存储短和整数值(例如System.TimeSpan ),类型本身是可比较的(与运算符一起使用),并且作为结构,可能不需要使其可克隆。

I do not have anything against that "status quo", it is only to satisfy my curiosity ;-) 我没有任何反对这种“现状”的东西,只是为了满足我的好奇心;-)

EDIT: Added comparison to System.TimeSpan . 编辑:添加了对System.TimeSpan的比较。

I can't say for sure, but one reason might be immutability. 我不能肯定地说,但是原因之一可能是不变性。 The properties in the Version class are all read-only. Version类中的属性都是只读的。 Whereas it's possible to declare readonly fields in a struct, Eric Lippert points that readonly on a struct field is a lie . 尽管可以在结构中声明readonly字段,但Eric Lippert指出, 在结构字段上只读是lie

Making it a class ensures immutability. 将其设置为类可确保不变性。

According to Microsoft's own guidelines , you should prefer a class to a structure when the instance is at least 16 bytes. 根据Microsoft 自己的指南 ,当实例至少为16个字节时,您应该更喜欢类而不是结构。 Since System.Version stores four Int32, each consisting of four bytes for a total of 16 bytes, they followed their own advice and made it a class. 由于System.Version存储了四个Int32,每个Int32包含四个字节,总共16个字节,因此他们遵循自己的建议并将其设为一个类。

Another point that may have been relevant in the design process is that Version is ComVisible. 在设计过程中可能涉及的另一点是Version是ComVisible。

As such, it makes more sense to expose it to COM as a coclass (behavior, without guarantees about internal layout) rather than as a COM struct (which specifies an in-memory layout like a C struct). 这样,将它作为一个共类(行为,不保证内部布局)公开给COM而不是作为COM结构(它指定一个像C结构那样的内存布局)更有意义。

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

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