在“using"语句中使用各种类型 (C#) [英] Using various types in a 'using' statement (C#)

查看:19
本文介绍了在“using"语句中使用各种类型 (C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

既然 C# using 语句只是 try/finally{dispose} 的一个语法糖,为什么它接受多个对象仅当它们是相同类型时?

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?

我不明白,因为它们只需要 IDisposable.如果他们都实现 IDisposable 应该没问题,但事实并非如此.

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.

特别是我习惯写作

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
}

但我不能.有人会说,我可能会写:

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.

推荐答案

你可以这样做:

using (IDisposable cmd = new SqlCommand(), con = (cmd as SqlCommand).Connection)
{
   var command = (cmd as SqlCommand);
   var connection = (con as SqlConnection);
   //code
}

也许这会让你满意.

这篇关于在“using"语句中使用各种类型 (C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆