使用语句的C#/ VB.NET是否实际上对未实现IDisposable的类执行任何操作

时间:2022-09-02 13:49:06

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? Myclass has not implemented the IDisposable interface so there isn't any Dispose() method to call. Am i thinking about this correctly?

在这种情况下,using语句实际上是否提供了任何用途? Myclass尚未实现IDisposable接口,因此没有任何Dispose()方法可以调用。我正确地考虑了这个吗?

2 个解决方案

#1


If your class is not implementing IDisposable then you can't use it inside using statement. It would be a compile time error.

如果您的类没有实现IDisposable,那么您不能在using语句中使用它。这将是一个编译时错误。

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). There is nothing magical done by CLR to actually dispose the object, it all depends on the implementation of Dispose. You can have an empty implementation of Dispose method and there will be no effect.

除此之外,using语句转换为try-finally块,在using语句结束时,调用Dispose(即使出现异常)。 CLR没有做任何神奇的实际处理对象,这完全取决于Dispose的实现。您可以使用Dispose方法的空实现,但不会产生任何影响。

#2


You cannot use using with types that don't implement IDisposable. You will get a compiler error. That's it.

您不能使用不实现IDisposable的类型。您将收到编译器错误。而已。

  • MSDN C#: ... All such types must implement the IDisposable interface....
  • MSDN C#:...所有这些类型必须实现IDisposable接口....

  • MSDN VB.NET ...Required. The class of the resource. The class must implement the IDisposable interface...
  • MSDN VB.NET ...必需。资源的类。该类必须实现IDisposable接口...

This is the CS1674 compiler error you get.

这是您获得的CS1674编译器错误。

#1


If your class is not implementing IDisposable then you can't use it inside using statement. It would be a compile time error.

如果您的类没有实现IDisposable,那么您不能在using语句中使用它。这将是一个编译时错误。

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). There is nothing magical done by CLR to actually dispose the object, it all depends on the implementation of Dispose. You can have an empty implementation of Dispose method and there will be no effect.

除此之外,using语句转换为try-finally块,在using语句结束时,调用Dispose(即使出现异常)。 CLR没有做任何神奇的实际处理对象,这完全取决于Dispose的实现。您可以使用Dispose方法的空实现,但不会产生任何影响。

#2


You cannot use using with types that don't implement IDisposable. You will get a compiler error. That's it.

您不能使用不实现IDisposable的类型。您将收到编译器错误。而已。

  • MSDN C#: ... All such types must implement the IDisposable interface....
  • MSDN C#:...所有这些类型必须实现IDisposable接口....

  • MSDN VB.NET ...Required. The class of the resource. The class must implement the IDisposable interface...
  • MSDN VB.NET ...必需。资源的类。该类必须实现IDisposable接口...

This is the CS1674 compiler error you get.

这是您获得的CS1674编译器错误。