如何用指令写几个?

Bas*_*mme 23 .net c# idisposable using

可能重复:
使用包含多个变量的语句

我有几个一次性物品要管理.CA2000规则要求我在退出范围之前处置所有对象..Dispose()如果我可以使用using子句,我不喜欢使用该方法.在我的具体方法中,我应该在使用中写许多:

using (Person person = new Person()) {
    using (Adress address = new Address()) { 
        // my code
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有可能以另一种方式写这个:

using (Person person = new Person(); Adress address = new Address())
Run Code Online (Sandbox Code Playgroud)

Jim*_*agg 30

您可以在using语句中声明两个或多个对象(以逗号分隔).缺点是它们必须是同一类型.

法律:

using (Person joe = new Person(), bob = new Person())
Run Code Online (Sandbox Code Playgroud)

非法:

using (Person joe = new Person(), Address home = new Address())
Run Code Online (Sandbox Code Playgroud)

您可以做的最好是嵌套using语句.

using (Person joe = new Person())
using (Address home = new Address())
{
  // snip
}
Run Code Online (Sandbox Code Playgroud)


Zdr*_*nev 20

你能做的最好的事情是:

using (Person person = new Person())
using (Address address = new Address())
{ 
    // my code
}
Run Code Online (Sandbox Code Playgroud)


Raw*_*ing 8

可以做到

using (IDisposable iPerson = new Person(), iAddress = new Address())
{
    Person person = (Person)iPerson;
    Address address = (Address)iAddress;
    //  your code
}
Run Code Online (Sandbox Code Playgroud)

但这并不是一个改进.


Cal*_*ith 6

如果它们属于同一类型,则只能在单个using语句中使用多个对象.您仍然可以使用不带括号的语句嵌套.

using (Person person = new Person())
using (Address address = new Address())
{

}
Run Code Online (Sandbox Code Playgroud)

以下是使用语句的多个对象,相同类型的示例:

using (Person p1 = new Person(), p2 = new Person())
{

}
Run Code Online (Sandbox Code Playgroud)