简体   繁体   English

为什么Uri是类而不是结构?

[英]Why is Uri a class and not a struct?

System.Uri seems to be a perfect candidate for being a struct but the good folks at Microsoft decided to make it a class . System.Uri似乎很适合作为struct但Microsoft的优秀人才决定使其成为一门class It is clearly a value object -> there is no sense in having two different instances of " https://stackoverflow.com " and so it has struct-y equality rules. 显然,它是一个值对象->拥有两个“ https://stackoverflow.com ”的不同实例毫无意义,因此它具有struct-y相等规则。 I can't see any setters on the public API either, so it is immutable. 我在公共API上也看不到任何设置器,因此它是不可变的。

Is there some implementation detail which dictates it must be a class ? 是否有一些实现细节规定它必须是class

A struct would always have a default constructor (where all fields would be initialized to their default values). struct始终具有默认构造函数(所有字段都将初始化为它们的默认值)。 This could cause issues, for example, with some of the internal fields. 例如,这可能会导致某些内部字段出现问题。

One example is that the existing constructor ensures that m_String can't be null - https://referencesource.microsoft.com/#system/net/system/UriExt.cs,39 . 一个示例是现有的构造函数确保 m_String不能为null- https : m_String If you made this a struct, you can't easily achieve that in C#. 如果将其作为结构,则无法在C#中轻松实现。 So, everywhere you read from m_String you'd need to add a null check (which is not required if it is a class). 因此,从m_String读取的每个地方都需要添加一个null检查(如果是类则不需要)。

Additionally, as others have pointed out, the docs have other guidance on choosing when to use struct : 此外,正如其他人指出的那样, 文档在选择何时使用struct还有其他指导:

✓ CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects. ✓如果类型的实例较小且通常为短寿命或通常嵌入在其他对象中,请考虑定义结构而不是类。

X AVOID defining a struct unless the type has all of the following characteristics: X AVOID定义一个结构,除非该类型具有以下所有特征:

It logically represents a single value, similar to primitive types (int, double, etc.). 它在逻辑上表示一个值,类似于基本类型(int,double等)。

It has an instance size under 16 bytes. 它的实例大小小于16个字节。

It is immutable. 这是一成不变的。

It will not have to be boxed frequently. 不必经常装箱。

The 16 byte requirement, in particular, is likely to be problematic for Uri . 对于Uri ,尤其是16字节的要求可能会出现问题。

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

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