How to detect if an object is within a 'using' scope?
Please see my example code:
var testObject = new SomeClass();
using (testObject)
{
//At this point how can the testObject implicitly know
开发者_StackOverflow中文版 //if it is placed inside a 'using' scope?
// In other words, how can testObject know that
// .SomeAction() is being called from within a 'using' scope?
testObject.someAction();
}
It can't.
It could get a stack dump to determine where the calling code is, and analyze the code to try to determine what it does. It could look for the try...finaly
and dispose
that the using
block generates, but it could still not tell if it actually was a using
block or not.
You can't. It would not make any difference anyway. All you are doing is creating the object, calling some methods, then disposing it. Why should the behaviour of someAction
change depending on whether or not Dispose
is called some time in the future?
I'd like to construct an object that can only have it's methods called if it is placed within a 'using' scope.
No, that's not possible.
The only reason why you'd want functionality like that is to make a guarantee that an object always get's disposed when it leaves scope, and there are much better ways to enforce this logic.
If you're using VS2010, then you can use FxCop's Dispose objects before losing scope for objects implementing IDisposable
. In the event you create an object without disposing it, FxCop will fail your build -- and that's about as good of a compiler guarantee as you can get for your requirements.
精彩评论