【发布时间】:2019-12-03 20:02:19
【问题描述】:
我想知道object initializers inside using statements 的使用是否会以某种方式阻止正确处理其中声明的资源,例如
using (Disposable resource = new Disposable() { Property = property })
{
// ...
}
我读过对象初始化器不过是同步糖,编译器会将其转换为类似于以下代码的内容:
MyClass tmp = new MyClass();
tmp.Property1 = 1;
tmp.Property2 = 2;
actualObjectYouWantToInitialize = tmp;
即使我可能看起来像一个困惑无知的人,我也想要求澄清一下。初始化对象(据我所知)是指向另一个对象的指针(据我所知,这也是一个指针)这一事实是否会干扰using 语句完成的资源处置?
【问题讨论】:
-
@TimSchmelter 我刚刚用以下类测试了这个:
public class Test : IDisposable { public string Property { get => "Hello"; set => throw new Exception();} public void Dispose() { Console.WriteLine("Disposed"); } }。运行using(var x = new Test() { Property = "Test"})时未调用 Dispose。 -
@JonathonChase 有趣,我认为这是因为编译器将
using转换为的try-finally在调用Dispose()之前检查资源是否为null,它是初始化失败的时候。 -
@StackLloyd 许多人都有设置
resource变量的心理模型,并在其上设置了 then 属性(这是错误的)。这种心智模式可能就是为什么有些人认为该对象将被处置的原因。
标签: c# using-statement object-initializers