C# 带有多个变量的 using 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9396064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:11:52  来源:igfitidea点击:

using statement with multiple variables

c#using-statement

提问by Antony Scott

Is it possible to make this code a little more compact by somehow declaring the 2 variable inside the same using block?

是否可以通过在同一个 using 块中以某种方式声明 2 变量来使此代码更紧凑一些?

using (var sr = new StringReader(content))
{
    using (var xtr = new XmlTextReader(sr))
    {
        obj = XmlSerializer.Deserialize(xtr) as TModel;
    }
}

采纳答案by Konrad Rudolph

The accepted way is just to chain the statements:

接受的方法只是链接语句:

using (var sr = new StringReader(content))
using (var xtr = new XmlTextReader(sr))
{
    obj = XmlSerializer.Deserialize(xtr) as TModel;
}

Note that the IDE will also support this indentation, i.e. it intentionally won't try to indent the second usingstatement.

请注意,IDE 也将支持这种缩进,即它不会故意尝试缩进第二个using语句。

回答by Frank Bollack

The following only works for instances of the same type!Thanks for the comments.

以下仅适用于相同类型的实例!感谢您的评论。

This sample code is from MSDN:

此示例代码来自MSDN

using (Font font3 = new Font("Arial", 10.0f), font4 = new Font("Arial", 10.0f))
{
    // Use font3 and font4.
}