Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

c# - Is it possible to force the use of "using" for disposable classes?

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"
{
}
question from:https://stackoverflow.com/questions/2675504/is-it-possible-to-force-the-use-of-using-for-disposable-classes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...