官方文档中的解释:
用 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(); } }