我可以在C#*中使用*块使用不同类型的对象吗?

Ran*_*ray 5 c# using

using (Font font3 = new Font("Arial", 10.0f), 
           font4 = new Font("Arial", 10.0f))
{
    // Use font3 and font4.
}
Run Code Online (Sandbox Code Playgroud)

我知道在using子句中可以使用多个相同类型的对象.

我不能在using子句中使用不同类型的对象吗?

好吧,我试过,但虽然他们是不同的名称和不同的对象,他们的行为相同=有相同的方法集

有没有其他方法可以使用不同类型的使用类?

如果没有,最合适的使用方法是什么?

Jes*_*alm 28

using(Font f1 = new Font("Arial",10.0f))
using (Font f2 = new Font("Arial", 10.0f))
using (Stream s = new MemoryStream())
{

}
Run Code Online (Sandbox Code Playgroud)

像这样?


thi*_*eek 10

不,你不能做这种方式,但你可以nestusing块.

using (Font font3 = new Font("Arial", 10.0f))
{ 
    using (Font font4 = new Font("Arial", 10.0f))
    {
        // Use font3 and font4.
    }
}
Run Code Online (Sandbox Code Playgroud)

或者像其他人说的那样,但由于可读性,我不会这样推荐.

using(Font font3 = new Font("Arial", 10.0f))
using(Font font4 = new Font("Arial", 10.0f))
{
    // use font3 and font4
}
Run Code Online (Sandbox Code Playgroud)

  • 说实话 - 我觉得后者更具可读性.如果要初始化三个或四个项目(例如流,流读取器,流,流写器),嵌套可能会完全失控!我想这可能是你习惯的. (10认同)

Sco*_*ott 6

您可以使用语句进行堆叠来完成此任务:

using(Font font3 = new Font("Arial", 10.0f))
using(Font font4 = new Font("Arial", 10.0f))
{
    // use font3 and font4
}
Run Code Online (Sandbox Code Playgroud)


Joã*_*elo 5

using语句的目的是保证通过调用接口Dispose提供的方法显式地处理获取的资源IDisposable.规范不允许您在单个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);
}
Run Code Online (Sandbox Code Playgroud)

但是,我不推荐这个,我认为这是滥用,所以这个答案只是说你可以破解它,但你可能不应该.