使用 C# using 语句延迟实例化
有没有办法编写 using
语句而不立即实例化 IDisposable
?
例如,如果我需要做类似的事情:
using (MyThing thing)
{
if (_config == null)
{
thing = new MyThing();
}
else
{
thing = new MyThing(_config);
}
// do some stuff
} // end of 'using'
对于这样的情况是否有可接受的模式?或者我是否再次显式处理 IDisposable
?
Is there any way to write a using
statement without instantiating the IDisposable
immediately?
For example, if I needed to do something like:
using (MyThing thing)
{
if (_config == null)
{
thing = new MyThing();
}
else
{
thing = new MyThing(_config);
}
// do some stuff
} // end of 'using'
Is there an accepted pattern for cases like this? Or am I back to handling the IDisposable
explicitly again?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,在您的示例中,您确实立即实例化一次性对象 - 仅基于条件。例如,您可以使用:
为了更通用,您可以使用一种方法:
棘手的一点是实例化的时间是否根据各种条件而改变。这确实会更难使用
using
语句来处理,但也会建议您应该尝试重构代码以避免该要求。这并不总是可行,但值得尝试。另一种替代方法是将“事物”封装在包装器中,该包装器将适当地延迟创建真正的一次性对象,并委托该对象进行处置以及您可以对该类型执行的任何其他操作。在某些情况下,这样的委派可能会很痛苦,但它可能是合适的 - 取决于您真正想要做什么。
Well, in your example you do instantiate the disposable object immediately - just based on a condition. For example, you could use:
To be more general, you can use a method:
The tricky bit would be if the timing of the instantiation changed based on various conditions. That would indeed be harder to handle with a
using
statement, but would also suggest that you should try to refactor your code to avoid that requirement. It won't always be possible, but it's worth trying.Another alternative is to encapsulate the "thing" in a wrapper which will lazily create the real disposable object appropriately, and delegate to that for disposal and anything else that you can do with the type. Delegation like this can be a pain in some situations, but it might be appropriate - depending on what you're really trying to do.
你可以这样做:
You could do:
我认为最明智的解决方案是将配置的决定移至 MyThing 构造函数中。这样你就可以简化类的使用,如下所示:
I think the most sane solution is to move the decision of what to with the config into the MyThing constructor. That way you could simplify the usage of the class like so: