编辑
2025-09-29
C#
00

目录

摘要
正文
应用场景
示例 1: 基本的 ref struct 定义和使用
示例 2: 使用 ref struct 进行内存操作
结论

摘要

在 C# 7 中,引入了 ref struct 类型,这是一个特殊的值类型,它被设计为栈分配,并且不能在托管堆上分配。ref struct 类型的主要目的是为了提供一种安全和高效的方式来处理那些与内存操作相关的场景。

正文

应用场景

ref struct 类型主要应用于以下场景:

  1. 性能关键型代码:当需要避免堆分配和垃圾回收时,ref struct 可以减少内存分配和提升性能。
  2. 内存管理:用于封装对非托管资源的操作,如直接内存访问或处理原始指针。
  3. 跨越调用:与平台调用(P/Invoke)结合使用,用于与非托管代码交互。
  4. Span 和 Memoryref struct 在 .NET 的 System.Memory 类库中被广泛使用,在处理内存切片和缓冲区时提供了安全的API。

示例 1: 基本的 ref struct 定义和使用

C#
using C20240114C; public ref struct RefStructExample { public int X; public int Y; public RefStructExample(int x, int y) { X = x; Y = y; } public void Display() { Console.WriteLine($"X: {X}, Y: {Y}"); } } class Program { static void Main() { RefStructExample point = new RefStructExample(5, 10); point.Display(); // point 只能在栈上分配,不能作为成员变量,也不能装箱 } }

image.png

示例 2: 使用 ref struct 进行内存操作

C#
using C20240114C; public unsafe ref struct MemoryBlock { private void* _pointer; private int _size; public MemoryBlock(void* pointer, int size) { _pointer = pointer; _size = size; } public ref byte this[int index] { get { if (index >= _size || index < 0) { throw new IndexOutOfRangeException(); } return ref ((byte*)_pointer)[index]; } } public void ZeroMemory() { for (int i = 0; i < _size; i++) { this[i] = 0; } } } class Program { static unsafe void Main() { int size = 10; byte* buffer = stackalloc byte[size]; // 在栈上分配内存 MemoryBlock block = new MemoryBlock(buffer, size); block.ZeroMemory(); // 将内存块清零 } }

结论

ref struct 类型在 C# 中是一个强大的特性,它可以帮助开发者写出更高效和安全的代码,特别是在需要进行内存密集型操作或与非托管资源交互时。然而,由于 ref struct 的限制,它们不能被装箱、不能被捕获到 lambda 表达式或局部函数中、不能作为异步方法的局部变量,因此在使用时需要特别注意。适当使用时,ref struct 可以帮助你优化性能并减少垃圾回收的压力。

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!