这个问题已经在这里有了答案:
已关闭8年。
我有几个一次性物品要管理。 CA2000规则要求我在退出范围之前处置所有对象。如果可以使用using子句,我不喜欢使用.Dispose()
方法。在我的特定方法中,我应该在using中编写许多use:
using (Person person = new Person()) {
using (Adress address = new Address()) {
// my code
}
}
是否可以用其他方式编写此代码:
using (Person person = new Person(); Adress address = new Address())
最佳答案
您可以在using
语句中声明两个或多个对象(用逗号分隔)。缺点是它们必须是相同的类型。
合法:
using (Person joe = new Person(), bob = new Person())
非法:
using (Person joe = new Person(), Address home = new Address())
最好的办法是嵌套using语句。
using (Person joe = new Person())
using (Address home = new Address())
{
// snip
}
关于c# - 如何写几个使用说明? [复制],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13863200/