简体   繁体   English

C#/ VB.NET using语句实际上对未实现IDisposable的类做任何事情

[英]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. 而已。

  • MSDN C# : ... All such types must implement the IDisposable interface.... MSDN C# :...所有此类类型都必须实现IDisposable接口。
  • MSDN VB.NET ...Required. MSDN VB.NET ...必需。 The class of the resource. 资源的类别。 The class must implement the IDisposable interface... 该类必须实现IDisposable接口...

This is the CS1674 compiler error you get. 是您遇到的CS1674编译器错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用C#的“ using”语句和自定义对象的函数时,是否需要实现IDisposable? - Using C#'s 'using' statement with a custom object's function, do I Need to implement IDisposable? 在c#中使用vb.net类 - Using vb.net classes in c# 在C#中,是否可以使用具有不同名称的成员实现接口成员,就像在VB.NET中一样? - In C#, is it possible to implement an interface member using a member with a different name, like you can do in VB.NET? 为什么我的匿名类型在使用VB.Net但在C#中工作时不能在Clay中工作 - Why do my anonymous types not work in Clay when using VB.Net but do work in C# C#使用Statement和iDisposable - C# Using Statement and iDisposable 如何在C#中使用FileOpen(VB.NET)? - How do I use FileOpen (VB.NET) in C#? 如何将 VB.NET 中的扩展移植到 C#? - How do I port an extension in VB.NET to C#? vb.net 到 c# - 我们如何纠正这个错误 - vb.net to c# - how do we correct this error 在C#中使用抽象类时,AgressiveInlining会执行任何操作吗?应将其放在何处? - When using abstract classes in C#, does AgressiveInlining do anything, and where should it be placed? 如何在我的VB.net应用程序中使用c#web服务处理区分大小写的类和方法 - How do I handle case sensitive classes and methods from a c# web service in my VB.net app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM