在 using 语句中声明 2 个类型会出现编译错误吗?
我想使用这行代码:
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 示例有何不同?
I want to use this line of code:
using (ADataContext _dc = new ADataContext(ConnectionString), BDataContext _dc2 = new BrDataContext(ConnectionString)){ // ...}
This gives a compile error:
Cannot use more than one type in a
for, using, fixed or declartion
statement.
I thought this was possible? MSDN says it is: http://msdn.microsoft.com/en-us/library/yh598w02%28VS.80%29.aspx
In the MSDN sample code Font is used, which is class and thereby a reference type as well as my two DataContext classes.
What went wrong here? How does my attempt differ from the MSDN sample?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
MSDN 声明了两个相同类型对象的实例。您声明了多种类型,因此您收到了错误消息。
编辑:要全力以赴,语言规范第 8.13 节说:
当资源获取采用局部变量声明的形式时,可以获取给定类型的多个资源。 形式的 using 语句
完全等同于一系列嵌套的 using 语句:
关键是这些是给定类型的资源,而不是类型,与 MSDN 示例相匹配。
MSDN declared instances of two objects of the same type. You're declaring multiple types, hence the error message you received.
Edit: To go all "Eric Lippert" on it, section 8.13 of the language specification says:
When a resource-acquisition takes the form of a local-variable-declaration, it is possible to acquire multiple resources of a given type. A using statement of the form
is precisely equivalent to a sequence of nested using statements:
The key is that these are resources of a given type, not types, which matches the MSDN example.
改为执行此操作
Do this instead
using
资源获取语句可以是声明。声明只能声明一个类型的变量。你可以做:
但你不能
The
using
resource acquisition statement can be a declaration. A declaration can only declare variables of one type.You can do:
but you can't