Is it possible to force the use of “using” for disposable classes?

前端 未结 10 627
轮回少年
轮回少年 2020-12-05 06:49

I need to force the use of \"using\" to dispose a new instance of a class.

public class MyClass : IDisposable
{
   ...
}

using(MyClass obj = new MyClass())          


        
10条回答
  •  情深已故
    2020-12-05 07:29

    No, you cannot do that. You can't even force them to call dispose. The best you can do is add a finalizer. Just keep in mind that the finalizer will get called when the object is disposed and that is up to the runtime.

提交回复
热议问题