我可以在 C# *using* 块中拥有不同类型的对象吗?
using (Font font3 = new Font("Arial", 10.0f),
font4 = new Font("Arial", 10.0f))
{
// Use font3 and font4.
}
我知道可以在 using 子句中使用相同类型的多个对象。
我不能在 using 子句中使用不同类型的对象吗?
好吧,我尝试过,但尽管它们是不同的名称和不同的对象,但它们的行为相同=具有相同的方法集
是否有其他方法可以使用不同类型的 using 类?
如果没有,最合适的使用方式是什么?
using (Font font3 = new Font("Arial", 10.0f),
font4 = new Font("Arial", 10.0f))
{
// Use font3 and font4.
}
I know that multiple objects of same type can be used inside a using clause.
Cant i use different types of objects inside the using clause?
Well i tried but although they were different names and different objects, they acted the same = had the same set of methods
Is there any other way to use the using class with different types?
If not, what is the most appropriate way to use it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
像这样吗?
Like so?
不,您不能这样做,但您可以
嵌套
using
块。或者正如其他人所说,但由于可读性,我不推荐这样做。
No you can't do it this way, but you can
nest
theusing
blocks.or as others said, but I'd not recommend it that way because of readability.
您可以堆叠 using 语句来完成此操作:
You can stack using statements to accomplish this:
using 语句的目的是保证通过调用
IDisposable
接口提供的Dispose
方法来显式释放所获取的资源。该规范不允许您在单个 using 语句中获取不同类型的资源,但记住第一句话,您可以根据编译器编写这段完全有效的代码。但是,我不推荐这样做,并且我认为这是滥用行为,因此这个答案只是表明您可以绕过它,但您可能不应该这样做。
The using statement purpose is to guarantee that the acquired resources are explicitly disposed by a call to
Dispose
method provided by theIDisposable
interface. The specification does not allow you to acquire resources of different types inside a single using statement but having the first sentence in mind you can write this perfectly valid code in terms of the compiler.However, I'm not recommending this and I consider it abusive, so this answer is just to state that you can hack around it but you probably should not.
您可以用逗号分隔相同类型的项目 - 好吧,我所知道的是编译器不会抱怨。您还可以堆叠不同类型的 using () 语句(使用一组括号 {})。
http://adamhouldsworth.blogspot.com/2010/02/你不知道的事情.html
You can comma-delimit items of the same type - well, all I know is the compiler doesn't complain. You can also stack using () statements (use one set of brackets {}) of different types.
http://adamhouldsworth.blogspot.com/2010/02/things-you-dont-know.html
您只能在每个
using
块中初始化单一类型的对象。但是,您可以根据需要嵌套它们:You can only have a single type of object initialized in each
using
block. You can nest those as much as you want, however:您可以嵌套它们:
它们应该以相反的顺序放置(首先是 font4)。
编辑:
这与:
You can nest them:
They should dispose in reverse order (font4 first).
EDIT:
This is exactly the same as: