在using语句使用不同类型(C#) [英] using various types in a using statement (C#)
问题描述
由于using语句C#是只是尝试语法糖/ {最终处置}为什么它接受多个对象,只有当他们是同一类型的吗?
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.
推荐答案
您虽然可以做到这一点:
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.
这篇关于在using语句使用不同类型(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!