ReSharper 2025.2 Help

代码检查:冗余的固定指针声明

固定大小缓冲区字段是可用在不安全上下文中的结构成员,表示 C 风格的内联数组。 此类字段主要用于与本机代码的互操作。

在 C# 7.3 之前,访问可能位于 GC 可移动内存中的固定大小缓冲区的元素仅在使用 fixed 语句固定缓冲区后才被允许,而保证位于不可移动内存中的固定大小缓冲区可以直接进行索引。

public unsafe struct MyBufferWrapper { public fixed byte Buffer[4]; public int Foo() => Buffer[0] + Buffer[1] + Buffer[2] + Buffer[3]; // error before C# 7.3 public int Bar() { fixed (byte* ptr = Buffer) { return ptr[0] + ptr[1] + ptr[2] + ptr[3]; // ok } } }

在仅用于访问固定大小缓冲区元素的情况下,引入辅助固定指针声明的要求是不合理的,因为除非缓冲区的地址被存储在某处,否则索引始终是安全的。

C# 7.3 移除了对可移动固定大小缓冲区进行索引的不必要限制,使其使用更加自然:

public unsafe struct MyBufferWrapper { public fixed byte Buffer[4]; public int Foo() => Buffer[0] + Buffer[1] + Buffer[2] + Buffer[3]; // ok since C# 7.3 public int Bar() { byte* ptr = Buffer; // error: taking address of the fixed size buffer still requires pinning return ptr[0] + ptr[1] + ptr[2] + ptr[3]; } }

ReSharper 检测到使用 fixed 语句不必要的地方,并提供快速修复以移除冗余的固定指针声明。

最后修改日期: 2025年 9月 27日