【问题标题】:Declare 2 types inside using statement gives compile error?在 using 语句中声明 2 种类型会产生编译错误?
【发布时间】:2011-01-31 23:32:45
【问题描述】:

我想用这行代码:

using (ADataContext _dc = new ADataContext(ConnectionString), BDataContext _dc2 = new BrDataContext(ConnectionString)){ // ...}

这会导致编译错误:

不能在一个类型中使用多个类型 为、使用、固定或声明 声明。

我认为这是可能的? MSDN 说是:http://msdn.microsoft.com/en-us/library/yh598w02%28VS.80%29.aspx 在 MSDN 示例代码中使用了 Font,它是类,因此是引用类型以及我的两个 DataContext 类。

这里出了什么问题?我的尝试与 MSDN 示例有何不同?

【问题讨论】:

    标签: c# using-statement


    【解决方案1】:

    MSDN 声明了两个相同类型对象的实例。您声明了多种类型,因此您收到了错误消息。

    编辑:要全部使用“Eric Lippert”,语言规范的第 8.13 节说:

    当资源获取采用局部变量声明的形式时,可以获取给定类型的多个资源。形式的 using 语句

    using (ResourceType r1 = e1, r2 = e2, ..., rN = eN) statement
    

    正好等价于一系列嵌套的 using 语句:

    using (ResourceType r1 = e1)
        using (ResourceType r2 = e2)
            ...
                using (ResourceType rN = eN)
                    statement
    

    关键是这些是给定类型的资源,而不是与 MSDN 示例匹配的类型。

    【讨论】:

      【解决方案2】:

      改为这样做

      using (ADataContext _dc = new ADataContext(ConnectionString))
      using (BDataContext _dc2 = new BrDataContext(ConnectionString))
      { // ...}
      

      【讨论】:

      • 我实际上认为在这种情况下,更少的大括号等于更高的可读性。
      【解决方案3】:

      using 资源获取语句可以是声明。一个声明只能声明 一个 类型的变量。

      你可以这样做:

      using (TypeOne t = something, t2 = somethingElse) { ... }
      // Note that no type is specified before `t2`. Just like `int a, b`
      

      但你不能

      using (TypeOne t = something, TypeTwo t2 = somethingElse) { ... }
      

      【讨论】:

        猜你喜欢
        • 2023-03-19
        • 2019-11-20
        • 1970-01-01
        • 2011-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多