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

Lea*_*ner 3 .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
Run Code Online (Sandbox Code Playgroud)

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

luk*_*san 6

怎么样TryCastIDisposableUsing:

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
Run Code Online (Sandbox Code Playgroud)

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

如果在.NET 3.5中运行,则TryCast()返回NothingUsing忽略.

似乎没有成为所需的任何清理SmtpClient在.NET 3.5,因为他们没有提供Dispose()或任何其他清理方法,据我可以告诉.