在“using”中使用各种类型 声明(C#)
既然 C# using
语句只是 try/finally{dispose} 的语法糖,为什么它只接受多个相同类型的对象呢?
我不明白,因为它们需要的只是 IDisposable。 如果它们都实现 IDisposable 应该没问题,但事实并非如此。
具体来说,我习惯于
using (var cmd = new SqlCommand())
{
using (cmd.Connection)
{
// Code
}
}
将其压缩为:
using (var cmd = new SqlCommand())
using (cmd.Connection)
{
// Code
}
我想进一步压缩为:
using(var cmd = new SqlCommand(), var con = cmd.Connection)
{
// Code
}
但我不能。 有些人可能会说,我可能会写:
using((var cmd = new SqlCommand()).Connection)
{
// Code
}
因为我需要处理的只是连接而不是命令,但这不是重点。
Since the C# using
statement is just a syntactic sugar for try/finally{dispose}, why does it accept multiple objects only if they are of the same type?
I don't get it since all they need to be is IDisposable. If all of them implement IDisposable it should be fine, but it isn't.
Specifically I am used to writing
using (var cmd = new SqlCommand())
{
using (cmd.Connection)
{
// Code
}
}
which I compact into:
using (var cmd = new SqlCommand())
using (cmd.Connection)
{
// Code
}
And I would like to compact furthermore into:
using(var cmd = new SqlCommand(), var con = cmd.Connection)
{
// Code
}
but I can't. I could probably, some would say, write:
using((var cmd = new SqlCommand()).Connection)
{
// Code
}
since all I need to dispose is the connection and not the command but that's besides the point.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不过你可以这样做:
也许这会让你满意。
You can do this though:
Perhaps that would be satisfactory to you.
没有特别好的技术原因; 我们本可以想出一种允许非同质类型的多个声明的语法。 鉴于我们没有这样做,并且已经有一个非常好的、清晰的、可理解的和相当简洁的机制来声明使用不同类型的块的嵌套,我们不太可能仅仅为了节省一些击键而添加新的语法糖。
There's no particularly good technical reason; we could have come up with a syntax that allowed multiple declarations of nonhomogeneous types. Given that we did not, and there already is a perfectly good, clear, understandable and fairly concise mechanism for declaring nested using blocks of different types, we're unlikely to add a new syntactic sugar just to save a few keystrokes.
C# 中的其他变量声明仅允许您在同一语句中声明相同类型的多个变量; 我不明白为什么
using
标头应该不同。Other variable declarations in C# only allow you to declare multiple variables of the same type in the same statement; I don't see why
using
headers should be different.我个人的使用方式可能符合要求:
不,这不是一行中
using
子句的两个实例,但它与您在示例中尝试的那样紧凑。更重要的是,您可以通过将连接字符串转换为私有属性来使其更加紧凑和程序员友好:
现在,上面
Test()
中的第一段代码可以缩短为以下内容:使编码变得非常好。
My personal way of using this might fit the bill:
No, this is not two instances of the
using
clause in one line, but it is as compact as you are trying to get in your example.What's more, you can make this even more compact and programmer friendly by turning your connection string into a Private Property:
Now, that first bit of code above in
Test()
could be shortened to the following:That makes coding very nice.