我喜欢using(){}语句来控制范围和可读性 . 您不仅可以创建对象,使用它们并巧妙地处理它们,还可以像这样使用它:
假设myInstance是代码中其他位置的MyClass实例 - 即方法参数或其他东西
using (var t = myInstance) {
t.Foo= "Hello";
t.Bar= "World";
...
}
MyClass的定义:
public class MyClass : IDisposable
{
public string Foo {get; set;}
public string Bar {get; set;}
...
public void Dispose() {}
}
这使得代码更整洁,更具可读性(我觉得),并且更容易输入 . 但是,为了广泛使用它,您必须实现IDisposable . 在这种情况下,MyClass不需要在Dispose中实际处理任何内容,因此它是空的 .
My question is, is there any drawback to using IDisposable in this way?
我很欣赏SO上已经存在类似的问题,但我不认为这些问题涉及为此目的使用IDispose(或者它们指的是特定的类) .
EDIT:
好吧,所以我想我有点特定,但是's a wider point here. The using statement is a handy, very neat way to define an instance for a specific length of time, and then you can forget about it. Its seems unfair that this ability should be restricted to IDisposable objects only. Yes there'不仅仅是实例化然后设置为null,还有一定程度的懒惰,但是使用块使得它非常具体,实例的范围是什么 . Why shouldn't I be allowed to do it with non IDisposable classes?