[英]Does C#/VB.NET using statement actually do anything with classes that do not implement IDisposable
If i have something like the following: 如果我有类似以下内容:
public class Myclass{
//some resources
}
and then in another class i do the following: 然后在另一堂课中,我执行以下操作:
using(Myclass myclass = new Myclass()) {
// do things with myclass instance
}
Does the using statement in this case actually provide any use? 在这种情况下,using语句是否实际提供任何使用?
Myclass
has not implemented the IDisposable
interface so there isn't any Dispose()
method to call. Myclass
尚未实现IDisposable
接口,因此没有要调用的Dispose()
方法。 Am i thinking about this correctly? 我在正确考虑吗?
If your class is not implementing IDisposable
then you can't use it inside using
statement. 如果您的类未实现
IDisposable
则不能在using
语句中使用它。 It would be a compile time error. 这将是编译时错误。
Other than that, using
statement translates into try-finally
block and at the end of using statement, Dispose
is called (even in case of an exception) . 除此之外,
using
语句转换为try-finally
块,并在using语句结束时调用Dispose
(即使在发生异常的情况下) 。 There is nothing magical done by CLR to actually dispose the object, it all depends on the implementation of Dispose
. CLR 实际处置对象没有什么神奇的事情,这完全取决于
Dispose
的实现。 You can have an empty implementation of Dispose
method and there will be no effect. 您可以有一个空的
Dispose
方法实现,并且不会起作用。
You cannot use using
with types that don't implement IDisposable
. 您不能与不能实现
IDisposable
类型一起using
。 You will get a compiler error. 您将得到一个编译器错误。 That's it.
而已。
IDisposable
interface.... IDisposable
接口。 IDisposable
interface... IDisposable
接口... This is the CS1674 compiler error you get. 这是您遇到的CS1674编译器错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.