【问题标题】:c# struct weird behavior [duplicate]c# struct 奇怪的行为
【发布时间】:2020-06-16 13:12:42
【问题描述】:

在 c# struct 和 using 语句中发现了一些奇怪的行为。不知道为什么会这样。 示例结构:

public struct Thing : IDisposable {
    private bool _dispose;

    public void Dispose() {
        _dispose = true;
    }
    public bool GetDispose() {
        return _dispose;
    }
    public void SetDispose(bool dispose) {
        _dispose = dispose;
    }
}

以及这个结构的用法:

        var thing = new Thing();
        using (thing) {
            Console.WriteLine(thing.GetDispose());
        }
        Console.WriteLine(thing.GetDispose());

我希望在这里看到以下输出:

False
True

因为 Dispose() 方法在使用范围结束时被调用。 但我明白了:

False
False

如果我将 struct 更改为 class,或者使用 struct 并添加 thing.SetDispose(true);在使用范围内,我得到了预期的输出

False
True

我的问题是为什么我会用结构得到 False False? 我用调试器检查过,每次使用范围结束时都会调用 Dispose()。

【问题讨论】:

  • 看看生成的 IL 会很有趣
  • @pm100 Here you go
  • v struct -> class 时奇怪的、微妙的代码更改。寻呼飞碟先生
  • 为什么不使用“_dispose”的属性?

标签: c# .net-core struct idisposable


【解决方案1】:

结构体是值类型,所以在这段代码中,原始结构体将被复制到 using 语句中的新结构体中。

您最后的代码将被翻译成:

var thing = new Thing();                     //thing._dispose == false
using (Thing thing2 = thing) {               //thing2.dispose == false   
     Console.WriteLine(thing2.GetDispose()); //thing2.dispose == false
}                                            //thing2.dispose == true
                                             //BUT thing1.dispose == false
Console.WriteLine(thing.GetDispose());

您可以在这里阅读更多内容:https://ericlippert.com/2011/03/14/to-box-or-not-to-box/

【讨论】:

    猜你喜欢
    • 2015-07-09
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 2019-04-10
    • 2019-05-24
    相关资源
    最近更新 更多