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

前端 未结 10 624
轮回少年
轮回少年 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:27

    It's ugly, but you could do something like this:

        public sealed class DisposableClass : IDisposable
        {
            private DisposableClass()
            {
    
            }
    
            public void Dispose()
            {
                //Dispose...
            }
    
            public static void DoSomething(Action<DisposableClass> doSomething)
            {
                using (var disposable = new DisposableClass())
                {
                    doSomething(disposable);
                }
            }
        }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-05 07:37

    I wonder if FXCop could enforce that rule?

    0 讨论(0)
  • 2020-12-05 07:38

    The using statement is a shorthand that the compiler converts from:

    (using DisposableObject d = new DisposableObject()){}
    

    into:

    DisposableObject d = new DisposableObject()
    try
    {
    
    }
    finally
    {
        if(d != null) d.Dispose();
    }
    

    so you are more or less asking if it is possible to enforce writing a try/finally block that calls Dispose for an object.

    0 讨论(0)
提交回复
热议问题