C# 8.0 中的 Disposable ref structs(可处置的 ref 结构)
官方文档中的解释:
用 ref
修饰符声明的 struct
可能无法实现任何接口,因此无法实现 IDisposable
。 因此,要能够处理 ref struct
,它必须有一个可访问的 void Dispose()
方法。 此功能同样适用于 readonly ref struct
声明。
由于没有示例用法,开始一直看着摸不着头脑,因此在网上找了个实例,以供参考,希望有助于你我的理解。
ref
结构体不能实现接口,当然也包括 IDisposable
,因此我们不能在 using
语句中使用它们,如下错误实例:
class Program { static void Main(string[] args) { using (var book = new Book()) Console.WriteLine("Hello World!"); } } // 报错内容:Error CS8343 'Book': ref structs cannot implement interfaces ref struct Book : IDisposable { public void Dispose() { } }
现在我们可以通过在ref
结构中,添加Dispose
方法,然后 Book 对象就可以在 using
语句中引用了。
class Program { static void Main(string[] args) { using (var book = new Book()) { // ... } } } ref struct Book { public void Dispose() { } }
由于在 C# 8.0
版本 using
语句的简化,新写法:(book 对象会在当前封闭空间结束前被销毁)
class Program { static void Main(string[] args) { using var book = new Book(); // ... } }
另外两个实例:
internal ref struct ValueUtf8Converter { private byte[] _arrayToReturnToPool; ... public ValueUtf8Converter(Span<byte> initialBuffer) { _arrayToReturnToPool = null; } public Span<byte> ConvertAndTerminateString(ReadOnlySpan<char> value) { ... } public void Dispose() { byte[] toReturn = _arrayToReturnToPool; if (toReturn != null) { _arrayToReturnToPool = null; ArrayPool<byte>.Shared.Return(toReturn); } } }
internal ref struct RegexWriter { ... private ValueListBuilder<int> _emitted; private ValueListBuilder<int> _intStack; ... public void Dispose() { _emitted.Dispose(); _intStack.Dispose(); } }

本文来自博客园,作者:橙子家,欢迎微信扫码关注博主【橙子家czzj】,有任何疑问欢迎沟通,共同成长!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步