在using语句中声明2个类型会产生编译错误吗?
我想使用这行代码:
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示例代码中使用了Font,它是类,因此是引用类型以及我的两个DataContext类。
这里出了什么问题? 我的尝试与MSDN示例有何不同?
MSDN声明了两个相同类型的对象的实例。 您正在声明多种类型,因此会收到您收到的错误消息。
编辑:要使用所有“Eric Lippert”,语言规范的第8.13节说:
当资源获取采用局部变量声明的forms时,可以获取给定类型的多个资源。 表格的使用声明
using (ResourceType r1 = e1, r2 = e2, ..., rN = eN) statement
完全等同于嵌套的using语句序列:
using (ResourceType r1 = e1) using (ResourceType r2 = e2) ... using (ResourceType rN = eN) statement
关键是这些是给定类型的资源 ,而不是与MSDN示例匹配的类型。
这样做
using (ADataContext _dc = new ADataContext(ConnectionString)) using (BDataContext _dc2 = new BrDataContext(ConnectionString)) { // ...}
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) { ... }