using statement with multiple variables [duplicate]

这一生的挚爱 提交于 2019-11-26 22:30:52

问题


This question already has an answer here:

  • Nested using statements in C# 17 answers

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

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

回答1:


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 using statement.




回答2:


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

This sample code is from MSDN:

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


来源:https://stackoverflow.com/questions/9396064/using-statement-with-multiple-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!