【问题标题】:How write several using instructions? [duplicate]怎么写几个使用说明? [复制]
【发布时间】:2012-12-01 12:58:48
【问题描述】:

可能重复:
using statement with multiple variables

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

using (Person person = new Person()) {
    using (Adress address = new Address()) { 
        // my code
    }
}

是否可以这样写:

using (Person person = new Person(); Adress address = new Address())

【问题讨论】:

  • 你想用的东西会变得很混乱......它也不是有效的语法。

标签: c# .net idisposable using


【解决方案1】:

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

法律:

using (Person joe = new Person(), bob = new Person())

非法:

using (Person joe = new Person(), Address home = new Address())

你能做的最好的就是嵌套 using 语句。

using (Person joe = new Person())
using (Address home = new Address())
{
  // snip
}

【讨论】:

    【解决方案2】:

    你能做的最好的就是:

    using (Person person = new Person())
    using (Address address = new Address())
    { 
        // my code
    }
    

    【讨论】:

      【解决方案3】:

      可以

      using (IDisposable iPerson = new Person(), iAddress = new Address())
      {
          Person person = (Person)iPerson;
          Address address = (Address)iAddress;
          //  your code
      }
      

      但这几乎不是改进。

      【讨论】:

        【解决方案4】:

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

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

        这里是一个多对象的例子,相同类型的 using 语句:

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

        【讨论】:

          猜你喜欢
          • 2010-10-12
          • 2014-07-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-05
          • 1970-01-01
          相关资源
          最近更新 更多