1

为什么在使用和对象初始化程序的情况下不调用 Dispose() ?我有以下代码:

public sealed class MyDisposeClass : IDisposable
{
    private int _value;

    public MyDisposeClass(string str)
    {
        Console.WriteLine($"MyDisposeClass: {str}");
    }

    public int Value
    {
        get => _value;
        set => _value = value / 0;
    }

    public void Dispose()
    {
        Console.WriteLine("Dispose");
    }
}

public static class MyProgram
{
    public static void Go()
    {
        Console.WriteLine("BEFORE USING");
        using (new MyDisposeClass("message") { Value = 100 })
        {
            Console.WriteLine("INSIDE USING");
        }

        Console.WriteLine("AFTER USING");
    }
}

class Program
{
    static void Main()
    {
        MyProgram.Go();
        Console.ReadKey();
    }
}

IlSpy 向我展示了这一点:

public static void Go()
{
    Console.WriteLine("BEFORE USING");
    using (new MyDisposeClass("message")
    {
        Value = 100
    })
    {
        Console.WriteLine("INSIDE USING");
    }
    Console.WriteLine("AFTER USING");
}

和 ILCode:

// [29 9 - 29 10]
IL_0000: nop

// [30 13 - 30 47]
IL_0001: ldstr        "BEFORE USING"
IL_0006: call         void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop

// [31 13 - 31 66]
IL_000c: ldstr        "message"
IL_0011: newobj       instance void ClassLibrary1.MyDisposeClass::.ctor(string)
IL_0016: dup
IL_0017: ldc.i4.s     100 // 0x64
IL_0019: callvirt     instance void ClassLibrary1.MyDisposeClass::set_Value(int32)
IL_001e: nop
IL_001f: stloc.0      // V_0
.try
{

  // [32 13 - 32 14]
  IL_0020: nop

  // [33 17 - 33 51]
  IL_0021: ldstr        "INSIDE USING"
  IL_0026: call         void [mscorlib]System.Console::WriteLine(string)
  IL_002b: nop

  // [34 13 - 34 14]
  IL_002c: nop
  IL_002d: leave.s      IL_003a
} // end of .try
finally
{

  IL_002f: ldloc.0      // V_0
  IL_0030: brfalse.s    IL_0039
  IL_0032: ldloc.0      // V_0
  IL_0033: callvirt     instance void [mscorlib]System.IDisposable::Dispose()
  IL_0038: nop

  IL_0039: endfinally
} // end of finally

// [35 13 - 35 46]
IL_003a: ldstr        "AFTER USING"
IL_003f: call         void [mscorlib]System.Console::WriteLine(string)
IL_0044: nop
4

0 回答 0