为什么在使用块和对象初始化器的情况下不调用 Dispose

问题描述

为什么在使用对象初始值设定项时不调用 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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)