Is it possible to force the use of “using” for dis

2019-01-13 20:40发布

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()) // Force to use "using"
{
}

10条回答
We Are One
2楼-- · 2019-01-13 20:47

I wonder if FXCop could enforce that rule?

查看更多
神经病院院长
3楼-- · 2019-01-13 20:48

The fact that you need to ensure that the object is disposed indicates a design flaw. It's fine if disposing is the polite or efficient thing to do, but it should not be semantically necessary.

There is no way to enforce that an object is disposed of via the using statement. However, what you can do is maintain a flag in the object that indicates whether the object was disposed or not, and then write a finalizer that checks that flag. If the finalizer detects that the object wasn't disposed, then you can have the finalizer, say, terminate the process via failfast. That is, so severely punish the user who neglected to dispose the object that they are forced to either fix their bug or stop using your object.

That doesn't strike me as nice, good, or polite, but you're the only one who knows what the terrible, terrible consequences are of failing to dispose the object. Whether applying a punishment to people who fail to follow your crazy rules is better than living with the consequences of them failing to follow the rules is for you to decide.

查看更多
疯言疯语
4楼-- · 2019-01-13 20:51

No it is not possible. Now what you can do is call the dispose method in the finalizer of the class (and then you can suppress the use of it if they do actually call the dispose method). That way it will fire if not done explicitly in code.

This link will show you how to implement the finalizer / dispose pattern:

http://www.devx.com/dotnet/Article/33167

查看更多
手持菜刀,她持情操
5楼-- · 2019-01-13 20:51

If you want force to use using on this class, your code to support this class you might code in other class and hide MyClass for normal use.

查看更多
仙女界的扛把子
6楼-- · 2019-01-13 20:52

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);
            }
        }
    }
查看更多
该账号已被封号
7楼-- · 2019-01-13 20:54

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.

查看更多
登录 后发表回答