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

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

问题描述

由于C# using 语句只是try / finally {dispose}的语法糖,所以为什么它只接受相同对象的多个对象输入



我不明白,因为它们所需要的只是IDisposposable。如果所有人都实现IDisposable,那应该没问题,但事实并非如此。



特别是我习惯于写

 使用(var cmd = new SqlCommand())
{
使用(cmd.Connection)
{
//代码
}
}

我压缩为:

 使用(var cmd = new SqlCommand())
使用(cmd.Connection)
{
//代码
}

我想进一步压缩为:

  using(var cmd = new SqlCommand(),var con = cmd.Connection)
{
//代码
}

但我不能。我可能会说:

  using((var cmd = new SqlCommand())。Connection)
{
//代码
}

因为我需要处理所有是连接而不是命令,但这不是重点。

解决方案

您可以执行以下操作:

 使用(IDisposable cmd = new SqlCommand(),con =(cmd as SqlCommand).Connection)
{
var command = (cmd为SqlCommand);
var connection =(con as SqlConnection);
//代码
}

也许您会满意。 / p>

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.

解决方案

You can do this though:

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

Perhaps that would be satisfactory to you.

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

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