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
using statement with multiple variables
提问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语句。

