[英]Using statement in C# without implementing Dispose Method
I am trying to understand using block in C#. 我试图理解在C#中使用块。 Can I create a custom object inside Using statement like the below which doesn't implement the IDisposable interface?
我可以在Using语句中创建一个自定义对象,如下所示,它不实现IDisposable接口吗?
Class A
{
}
using(A a = new A())
{
}
It gives me error saying "Error 1 'ConsoleApplication1.A': type used in a using statement must be implicitly convertible to 'System.IDisposable'" 它给出了错误,说“错误1'ConsoleApplication1.A':在using语句中使用的类型必须可以隐式转换为'System.IDisposable'”
How to correct this error? 如何更正此错误? I do not want to do Class A : IDisposable
我不想做A类:IDisposable
Any other way? 还有其他方法吗? Or it is a mandatory requirement that we need to implement IDisposable Dispose method in these kind of custom objects which we use inside using block?
或者强制要求我们需要在这些使用块内部使用的自定义对象中实现IDisposable Dispose方法?
EDIT: I am NOT expecting the definition that is there in the MSDN and thousands of websites. 编辑:我不期望MSDN和数千个网站中的定义。 I am just trying to understand this error and also the rectification
我只是想了解这个错误以及整改
Using blocks are syntactic sugar and only work for IDisposable objects. 使用块是语法糖,仅适用于IDisposable对象。
The following using statement: 以下使用声明:
using (A a = new A()) {
// do stuff
}
is syntactic sugar for: 语法糖是:
A a = null;
try {
a = new A();
// do stuff
}
finally {
if (!Object.ReferenceEquals(null, a))
a.Dispose();
}
The whole point of using is to create the equivalent of a try block with a call to Dispose in finally. 使用的重点是通过最终调用Dispose来创建try块的等价物。 If there is no Dispose method, there is no point to the using statement.
如果没有Dispose方法,则没有指向using语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.