'使用'System.Net.Mail.SmtpClient'类型的操作数必须实现'System.IDisposable' - (.NET 3.5)

时间:2013-01-25 15:03:06

标签: .net vb.net idisposable smtpclient

我有一个要求,我需要将.NET 4.0项目转换为.NET 3.5项目, 其他一切都很好,除了“SmtpClient” 到目前为止,我发现.NET 3.5 SmtpClient没有实现IDisposable,而在.NET 4.0中它确实实现了!

以下是在.NET4.0上运行良好但在.NET3.5上运行的代码:

Using MailServer As New SmtpClient(MailServerName)
MailServer.Credentials = New System.Net.NetworkCredential(MailServerUserName, MailServerPassword)
SendMail(MailServer, msgBody, msgSubject, FromEmail, ToEmail)
End Using

任何想法如何使用.NET 3.5(我更喜欢使用“使用”代码块来自动处理对象&而不是旧式手动配置)

3 个答案:

答案 0 :(得分:6)

TryCast之前的IDisposableUsing怎么样:

Dim MailServer As New SmtpClient(MailServerName)
Using TryCast(MailServer, IDisposable)
    MailServer.Credentials = New System.Net.NetworkCredential(MailServerUserName, MailServerPassword)
    SendMail(MailServer, msgBody, msgSubject, FromEmail, ToEmail)
End Using

如果在.NET 4.0中运行,TryCast()将返回SmtpClient,因为它实现了IDisposable。

如果在.NET 3.5中运行,则TryCast()会返回Nothing并忽略Using

在.NET 3.5中似乎没有SmtpClient所需的任何清理,因为据他所知,它们没有提供Dispose()或任何其他清理方法。

答案 1 :(得分:2)

您必须明确地编写Using语句的等价物。像这样:

    Dim MailServer As New SmtpClient(MailServerName)
    Try
        '' etc..
    Finally
        Dim disp = TryCast(MailServer, IDisposable)
        If disp IsNot Nothing Then disp.Dispose()
    End Try

答案 2 :(得分:2)

以下为我工作(使用.NET 3.5):

Dim MailServer = New SmtpClient(MailServerName)
Using TryCast(MailServer, IDisposable)
    MailServer.Credentials = New System.Net.NetworkCredential(MailServerUserName,MailServerPassword)
    SendMail(MonthlyMailServer, msgBody, msgSubject, FromEmail, ToEmail)
End Using