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();
}
}
參考自:Disposable ref structs in C# 8.0