我可以使用*块在C#*中使用不同类型的对象吗?
using (Font font3 = new Font("Arial", 10.0f), font4 = new Font("Arial", 10.0f)) { // Use font3 and font4. }
我知道在using子句中可以使用多个相同类型的对象。
我不能在using子句中使用不同类型的对象吗?
好吧,我试过,但虽然他们是不同的名称和不同的对象,他们的行为相同=有相同的方法集
有没有其他方法可以使用不同类型的使用类?
如果没有,最合适的使用方法是什么?
using(Font f1 = new Font("Arial",10.0f)) using (Font f2 = new Font("Arial", 10.0f)) using (Stream s = new MemoryStream()) { }
像这样?
不,你不能这样做,但你可以nest
using
块。
using (Font font3 = new Font("Arial", 10.0f)) { using (Font font4 = new Font("Arial", 10.0f)) { // Use font3 and font4. } }
或者像其他人说的那样,但由于可读性,我不会这样推荐。
using(Font font3 = new Font("Arial", 10.0f)) using(Font font4 = new Font("Arial", 10.0f)) { // use font3 and font4 }
您可以使用语句堆栈来完成此任务:
using(Font font3 = new Font("Arial", 10.0f)) using(Font font4 = new Font("Arial", 10.0f)) { // use font3 and font4 }
using语句的目的是保证通过调用IDisposable
接口提供的Dispose
方法显式处理获取的资源。 规范不允许您在单个using语句中获取不同类型的资源,但考虑到第一句话,您可以根据编译器编写这个完全有效的代码。
using (IDisposable d1 = new Font("Arial", 10.0f), d2 = new Font("Arial", 10.0f), d3 = new MemoryStream()) { var stream1 = (MemoryStream)d3; stream1.WriteByte(0x30); }
但是, 我不推荐这个 ,我认为这是滥用,所以这个答案只是说你可以破解它,但你可能不应该。
你可以用逗号分隔相同类型的项目 – 好吧,我所知道的是编译器没有抱怨。 您还可以使用不同类型的using()语句(使用一组括号{})进行堆叠。
https://adamhouldsworth.blogspot.com/2010/02/things-you-dont-know.html
在每个using
块中只能初始化一种类型的对象。 您可以根据需要嵌套那些,但是:
using (Font font3 = new Font("Arial", 10.0f)) { using (Brush b4 = new Brush()) { } }
你可以嵌套它们:
using (Font font3 = new Font("Arial", 10.0f)) using (font4 = new Font("Arial", 10.0f)) { // Use font3 and font4. }
它们应该以相反的顺序排列(首先是font4)。
编辑:
这完全相同:
上述就是C#学习教程:我可以使用*块在C#*中使用不同类型的对象吗?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
using (Font font3 = new Font("Arial", 10.0f)) { using (font4 = new Font("Arial", 10.0f)) { // Use font3 and font4. } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1001665.html