In C# how to override the Finalize() method?

前端 未结 3 962
自闭症患者
自闭症患者 2021-01-12 04:38

Following function giving compilation error \"Do not override object.Finalize. Instead, provide a destructor.\"

protected override void Finalize()
{                  


        
3条回答
  •  猫巷女王i
    2021-01-12 05:06

    You don't.

    Listen to the compiler. You shouldn't override Finalize. Instead, you should implement IDisposible and override Dispose.

    Unless you explicitly need to free resources held directly by the object, you should be able to do everything you need to in the Dispose method.

    But if you must:

    public class MyClass
    {
        public MyClass() { ... } // Constructor
        public ~MyClass() { ... } // Destructor/Finalizer
    }
    

    Just be careful because Finalizers are tricky and if implemented improperly can carry some pretty hefty performance overhead.

提交回复
热议问题