gpt4 book ai didi

c# - 为什么 Uri 是类而不是结构?

转载 作者:太空宇宙 更新时间:2023-11-03 20:51:39 27 4
gpt4 key购买 nike

System.Uri 似乎是成为 struct 的完美候选者,但 Microsoft 的优秀人员决定将其设为 class。它显然是一个值对象 -> 具有“https://stackoverflow.com”的两个不同实例是没有意义的,因此它具有 struct-y 相等规则。我在公共(public) API 上也看不到任何 setter,因此它是不可变的。

是否有一些实现细节规定它必须是一个

最佳答案

struct 总是有一个默认构造函数(其中所有字段都将被初始化为它们的默认值)。例如,这可能会导致一些内部字段出现问题。

一个例子是现有构造函数确保 m_String 不能为空 - https://referencesource.microsoft.com/#system/net/system/UriExt.cs,39 .如果将其设为结构,则无法在 C# 中轻松实现。因此,无论您从 m_String 读取什么地方,您都需要添加一个 null 检查(如果它是一个类则不需要)。

此外,正如其他人指出的那样,docs关于选择何时使用 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:

It logically represents a single value, similar to primitive types (int, double, etc.).

It has an instance size under 16 bytes.

It is immutable.

It will not have to be boxed frequently.

对于 Uri,尤其是 16 字节的要求可能会出现问题。

关于c# - 为什么 Uri 是类而不是结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54572119/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com