简体   繁体   English

关于C#using语句,我做对了吗?

[英]am i doing it right regarding C# using statement?

both SmtpClient and MailMessage implements IDisposable so i thought of making my code like this SmtpClient和MailMessage都实现了IDisposable,所以我想到了使我的代码像这样

using (SmtpClient smtpClient = new SmtpClient("xxx", 587))
{
    smtpClient.Credentials = new System.Net.NetworkCredential("email", "pass");
    smtpClient.EnableSsl = true;

    using (MailMessage mail = new MailMessage())
    {
        mail.Subject = "subject";
        mail.From = new MailAddress("email", "name");
        mail.To.Add(new MailAddress("email"));
        mail.Body = "body";
        mail.IsBodyHtml = true;

        smtpClient.Send(mail);
    }  
}

am i doing it right using 2 using statements or only the first using statement is necessary? 我使用2个using语句正确执行还是只需要第一个using语句?

thanks 谢谢

There is nothing inherently wrong with having multiple using statements. 拥有多个using语句本质上没有错。 It keeps the lifetime of objects to the minimum which is not a bad thing to do. 它将对象的生存时间保持在最低限度,这不是一件坏事。

When nesting using statements, it's more idiomatic to do it without indentation: using语句嵌套时,不使用缩进就更惯用了:

using (SmtpClient smtpClient = new SmtpClient("xxx", 587))
using (MailMessage mail = new MailMessage())
{
    smtpClient.Credentials = new System.Net.NetworkCredential("email", "pass");
    smtpClient.EnableSsl = true;

    mail.Subject = "subject";
    mail.From = new MailAddress("email", "name");
    mail.To.Add(new MailAddress("email"));
    mail.Body = "body";
    mail.IsBodyHtml = true;

    smtpClient.Send(mail);
}

This isn't always possible, because you sometimes need to do some processing between the first and the second using . 这并非总是可能的,因为有时您需要在第一次和第二次using之间进行一些处理。 It works in your example, though. 但是,它在您的示例中有效。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM