static destructor

后端 未结 6 1686
情歌与酒
情歌与酒 2020-12-04 17:46

C# has static constructor which do some initialization (likely do some unmanaged resource initialization).

I am wondering if there is static destructor?

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 18:06

    This is the best way (ref: https://stackoverflow.com/a/256278/372666)

    public static class Foo
    {
        private static readonly Destructor Finalise = new Destructor();
    
        static Foo()
        {
            // One time only constructor.
        }
    
        private sealed class Destructor
        {
            ~Destructor()
            {
                // One time only destructor.
            }
        }
    }
    

提交回复
热议问题