在using语句中声明2个类型会产生编译错误吗?

cit*_*nas 7 c# using-statement

我想使用这行代码:

using (ADataContext _dc = new ADataContext(ConnectionString), BDataContext _dc2 = new BrDataContext(ConnectionString)){ // ...}
Run Code Online (Sandbox Code Playgroud)

这给出了编译错误:

不能在for,using,fixed或declartion语句中使用多个类型.

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

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

Ant*_*ram 13

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

编辑:要使用所有"Eric Lippert",语言规范的第8.13节说:

当资源获取采用局部变量声明的形式时,可以获取给定类型的多个资源.表格的使用声明

using (ResourceType r1 = e1, r2 = e2, ..., rN = eN) statement
Run Code Online (Sandbox Code Playgroud)

恰好等同于嵌套的using语句序列:

using (ResourceType r1 = e1)
    using (ResourceType r2 = e2)
        ...
            using (ResourceType rN = eN)
                statement
Run Code Online (Sandbox Code Playgroud)

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

  • 字.-------------- (5认同)

Cat*_*ICU 12

这样做

using (ADataContext _dc = new ADataContext(ConnectionString))
using (BDataContext _dc2 = new BrDataContext(ConnectionString))
{ // ...}
Run Code Online (Sandbox Code Playgroud)

  • 我实际上认为在这种情况下,更少的括号等于更多的可读性. (7认同)

Meh*_*ari 6

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

你可以做:

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

但你不能

using (TypeOne t = something, TypeTwo t2 = somethingElse) { ... }
Run Code Online (Sandbox Code Playgroud)