您可以在使用块内处理多个对象? [英] Can you dispose of multiple objects within a Using block?
问题描述
如何在使用声明中得到处理了吗?要照顾多个对象
How to take care of multiple objects getting disposed off in a Using statement?
样品code
using(MyClass obj = new MyClass())
{
MyOtherClass objOC= new MyOtherClass()
TextReader objTR = new StringReader(...);
// other code
}
MyClass的OBJ
将被设置在使用块结束,但后来怎么样
MyOtherClass objOC
和的TextReader objTR
。据我所知,他们不会得到处置,所以我应该有一个嵌套使用块存在,这样下面?我需要一个真正的宽屏幕显示器,如果对象的数量增加
MyClass obj
will be be disposed at the end of the Using block, but then what about
MyOtherClass objOC
and TextReader objTR
. As far as I know it they wont get disposed, so should I be having a nested Using block there, like this below? I will need a real wide screen monitor if the number of objects increase
下面是正确的?这个
using(MyClass obj = new MyClass())
{
using (MyOtherClass objOC= new MyOtherClass())
{
using (TextReader objTR = new StringReader(...))
{
//code using all three objects
}
}
// other code using just `MyClass obj`
}
MyClass的&放大器; MyOtherClass都实现的IDisposable
推荐答案
是的,你的code是正确的。以下是你可能想知道......一对夫妇的其他事情
Yes, your code is correct. Here's a couple other things you might want to be aware of...
您可以声明相同类型单一using语句的多个对象。从文档:
You can declare multiple objects of the same type in a single using statement. From the documentation:
using (Font font3 = new Font("Arial", 10.0f),
font4 = new Font("Arial", 10.0f))
{
// Use font3 and font4.
}
有关使用多个不同类型的对象,你可以使用单行语法来节省空间巢:
For using multiple objects of different types you can nest using the one-line syntax to save space:
using (MyClass obj = new MyClass())
using (MyOtherClass objOC= new MyOtherClass())
using (TextReader objTR = new StringReader(...))
{
// code using all three objects
}
这篇关于您可以在使用块内处理多个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!