7

我想使用这行代码:

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

这给出了一个编译错误:

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

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

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

4

3 回答 3

13

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

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

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

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

完全等价于一系列嵌套的 using 语句:

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

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

于 2010-03-25T23:11:19.537 回答
12

改为这样做

using (ADataContext _dc = new ADataContext(ConnectionString))
using (BDataContext _dc2 = new BrDataContext(ConnectionString))
{ // ...}
于 2010-03-25T23:13:00.313 回答
6

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) { ... }
于 2010-03-25T23:11:07.503 回答