• 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

  • 相关阅读:
    关于Unity自带的保存简单且持久化数据PlayerPrefs类的使用
    Coursera Algorithm Ⅱ week3 baseball
    LVGL 8.2图片缩放及旋转
    mysql学习笔记--单张表上的增删改查
    Kotlin内置函数let、run、apply的区别
    设计模式 - 概览
    深入剖析Golang中单例模式
    我做抖音小店无货源电商,2个月攒下16万!抖音电商真的好做吗?
    如何用python生成动态随机验证码图片
    SpringBoot集成ElasticSearch
  • 原文地址:https://www.cnblogs.com/czzj/p/16835004.html