2011-01-10 31 views
1

是否有任何方法可以在不立即实例化IDisposable的情况下编写using语句?使用c#使用陈述延迟实例化

例如,如果我需要做的是这样的:

using (MyThing thing) 
{ 
    if (_config == null) 
    { 
     thing = new MyThing(); 
    } 
    else 
    { 
     thing = new MyThing(_config); 
    } 

    // do some stuff 

} // end of 'using' 

是否有这样的情况下接受的模式?还是我回到明确处理IDisposable

+0

3(几乎)在一分钟内完全相同的响应。太好了! :D – Rob 2011-01-10 12:50:50

回答

4

那么,在你的例子中你立即实例化一次性对象 - 只是基于一个条件。例如,你可以使用:

using (MyThing thing = _config == null ? new MyThing() : new MyThing(_config)) 
{ 
    ... 
} 

更一般情况下,你可以使用的方法:

using (MyThing thing = CreateThing(_config)) 
{ 
} 

如果实例化的定时来改变基于各种条件棘手位将是。用using声明处理确实很难,但是建议您应该尝试重构代码以避免该要求。这并不总是可能的,但值得尝试。

另一种选择是将“东西”封装在一个包装中,该包装将适当地懒惰地创建一个可处理的对象,并将其委托给处理以及您可以对该类型执行的任何其他操作。像这样的代表团在某些情况下可能会很痛苦,但它可能是合适的 - 这取决于你真正想要做什么。

+0

一如既往,彻底和翔实,先生,谢谢。 – fearofawhackplanet 2011-01-10 13:10:07

2
using (MyThing thing = _config == null ? new MyThing() : new MyThing(_config)) 
{ 
    // .... 

} 
1

你可以这样做:

if (_config == null) 
{ 
    thing = new MyThing(); 
} 
else 
{ 
    thing = new MyThing(_config); 
} 

using (thing) 
{ 

    // do some stuff 
} 
1

我认为最明智的解决方案是与配置到MyThing构造运动什么的决定。这样你可以简化类的使用,如下所示:

using (MyThing thing = new MyThing(_config)) 
{ 

} 

class MyThing { 
    public MyThing() { 
    //default constructor 
    } 

    public MyThing(Config config) :this() { 
    if (config == null) 
    { 
     //do nothing, default constructor did all the work already 
    } 
    else 
    { 
     //do additional stuff with config 
    } 
    } 
}