在C#或[dispose]方法中使用[using]语句更好吗?这是否适用于外部(COM)对象? [英] Is it better to use the [using] statement in C# or the [dispose] method? Does this apply to external (COM) objects?

查看:416
本文介绍了在C#或[dispose]方法中使用[using]语句更好吗?这是否适用于外部(COM)对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 使用(FileStream fileStream = new FileStream(
logs / myapp.log,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
using (StreamReader streamReader = new StreamReader(fileStream))
{
this.textBoxLogs.Text = streamReader.ReadToEnd();
}
}

另一方面,当我处理System.Net.Mail,我被告知我需要Dispose()对象释放任何杂散锁。



有没有一致的指导?

解决方案

没有理由我可以想到除了在 Dispose()的另一个实现中手动调用 Dispose() ve创建,实现 IDisposable ),当您可以使用块封装在中的对象。使用块将对象的创建和处理放在try / catch / finally块中,以几乎 gaurantee,该对象将被正确处理。



编译器比我更可靠。或者你。 =)



MSDN记录了使用语句,并调用您可以在哪里获取 C#语言规范,您可以在其中查看第8.13节使用语句(至少在v4.0参考资料中为8.13),其中详细说明了使用语句及其使用方法。第五段给出以下内容:


使用语句被翻译成
三部分:获取,使用和
处置。资源的使用是
隐式包含在包含finally子句的try语句
中。这个
finally子句处理
资源。如果一个空资源是
被获取,那么没有调用Dispose是
,并且没有抛出异常。



What is better, the using directive, or the dispose directive when finished with an object?

 using(FileStream fileStream = new FileStream(
            "logs/myapp.log",
            FileMode.Open,
            FileAccess.Read,
            FileShare.ReadWrite))
        {
            using(StreamReader streamReader = new StreamReader(fileStream))
            {
                this.textBoxLogs.Text = streamReader.ReadToEnd();
            }
        }

On the other hand, when I'm dealing with System.Net.Mail, I'm told I need to Dispose() of the object to release any stray locks.

Is there any consistent guidance? How do I tell what is more appropriate in a given situation for a given object?

解决方案

There's no reason that I can think of to manually call Dispose(), other than in another implementation of Dispose() (for example in a class you've created that implements IDisposable) when you can wrap an object in a using block. The using block puts the creation and disposal of the object in a try/catch/finally block to pretty much gaurantee that the object will be disposed of correctly.

The compiler is more reliable than me. Or you. =)

MSDN documents the using statement and calls out where you can obtain the C# language specification where you can review section 8.13 "The using statement" (at least in the v4.0 reference it's 8.13) that gives a comprehensive explanation of the using statement and how to use it. The fifth paragraph gives the following:

A using statement is translated into three parts: acquisition, usage, and disposal. Usage of the resource is implicitly enclosed in a try statement that includes a finally clause. This finally clause disposes of the resource. If a null resource is acquired, then no call to Dispose is made, and no exception is thrown.

这篇关于在C#或[dispose]方法中使用[using]语句更好吗?这是否适用于外部(COM)对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆