ref struct 类型相关的错误和警告

  • CS8343ref structs 无法实现接口
  • CS8344foreach 语句无法对异步或迭代器方法中的枚举器进行操作,因为类型是 ref struct 或者是允许 ref struct 的类型参数。
  • CS8345字段或自动实现的属性不能是类型,除非它是 ref struct 的实例成员。
  • CS9048scoped 修饰符只能用于 refs 和 ref struct 值。
  • CS9050ref 字段无法引用 ref struct
  • CS9059:ref 字段只能在 ref struct 中声明。
  • CS9241:已指定 `ref struct`。
  • CS9242:`allows` 约束子句必须是指定的最后一个约束。
  • CS9243不允许将其他约束已知的类型参数的 ref struct 用作类。
  • CS9244:类型不能是 ref struct 或允许 ref struct 的类型参数,以便在泛型类型或方法中使用它作为参数。
  • CS9245:类型无法实现 ref struct 类型的接口成员。
  • CS9246:在允许 ref struct 的类型参数上无法访问非虚拟实例接口成员。
  • CS9247:foreach 语句无法对类型的枚举器进行操作,因为它是一个允许 ref struct 的类型参数,并且在编译时无法确定它是否实现了 IDisposable
  • CS9267迭代器的元素类型可能不是 ref 结构或允许 ref 结构的类型参数

ref 安全违规

  • CS8345字段或自动实现的属性不能是类型,除非它是 ref struct 的实例成员。
  • CS9048scoped 修饰符只能用于 refs 和 ref struct 值。
  • CS9050ref 字段无法引用 ref struct
  • CS9059ref 字段只能在 ref struct 中声明。

ref struct 类型可以包含 ref 字段。 其他类型不允许使用 ref 字段。 编译程序对 ref struct 类型的声明和使用强制执行限制,以对任何 ref struct 类型的实例强制执行 ref 安全规则:

  • 只有 ref struct 类型可以包含自动实现 ref 的属性。
  • 只有 ref struct 类型或 ref 变量才能具有 scoped 修饰符。
  • ref 字段只能在 ref struct 类型中声明。
  • ref 字段无法引用 ref struct 类型/

违反其中任一规则都会产生所列错误之一。 如果打算使用该语言功能,请将类型转换为 ref struct。 否则,请移除不允许的构造。

ref struct 接口实现

  • CS8343ref structs 无法实现接口
  • CS8344foreach 语句无法对异步或迭代器方法中的枚举器进行操作,因为类型是 ref struct 或者是允许 ref struct 的类型参数。
  • CS9241:已指定 `ref struct`。
  • CS9242:`allows` 约束子句必须是指定的最后一个约束。
  • CS9243不允许将其他约束已知的类型参数的 ref struct 用作类。
  • CS9244:类型不能是 ref struct 或允许 ref struct 的类型参数,以便在泛型类型或方法中使用它作为参数。
  • CS9245:类型无法实现 ref struct 类型的接口成员。
  • CS9246:在允许 ref struct 的类型参数上无法访问非虚拟实例接口成员。
  • CS9247:foreach 语句无法对类型的枚举器进行操作,因为它是一个允许 ref struct 的类型参数,并且在编译时无法确定它是否实现了 IDisposable
  • CS9267迭代器的元素类型可能不是 ref 结构或允许 ref 结构的类型参数

在 C# 13 之前,ref struct 类型无法实现接口;编译程序生成 CS8343。 从 C# 13 开始,ref struct 类型可以实现接口,但要遵循以下规则:

  • 无法将 ref struct 转换为它实现的接口的实例。 在参数为接口类型时,若你使用 ref struct 类型作为参数时,则此限制包括隐式转换。 该转换会导致装箱转换,这违反了 ref 安全性。
  • 实现接口的 ref struct 必须实现所有接口成员ref struct 必须实现接口包含默认实现的成员。

从 C# 13 开始,ref struct 可以用作泛型类型参数的类型实参,但前提是泛型类型参数具有 allows ref struct 反约束。 在使用 allows ref struct 反约束时,必须遵循以下规则:

  • ref struct 用作类型实参,类型参数必须具有 allows ref struct 反约束。- allows ref struct 反约束必须在该参数的 where 子句的末尾
  • 类型参数必须遵循 ref 安全规则来使用实例。
  • ref struct可以是类型ref struct的类型参数不能用作迭代器方法元素类型。