【发布时间】:2009-07-09 05:49:12
【问题描述】:
我正在编写一个简单的小类,其中包含一个发送电子邮件的方法。我的目标是在旧版 Visual Basic 6 项目中实现它,通过 COM 互操作工具将其作为 COM 对象公开。
我发现有一个细节很难解决,那就是我在验证参数时应该有多细。从这个角度来看,我真正不满意的一件事,而且根本不是细节,是我实际处理异常的方式:
public class MyMailerClass
{
#region Creation
public void SendMail(string from, string subject, string to, string body)
{
if (this.IsValidMessage(from, subject, to, body)) // CS1501
{
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;
msg.From = new MailAddress(from);
msg.To.Add(to);
msg.Subject = subject;
msg.Body = body;
SmtpClient srv = new SmtpClient("SOME-SMTP-HOST.COM");
srv.Send(msg);
}
else
{
throw new ApplicationException("Invalid message format.");
}
}
#endregion Creation
#region Validation
private bool IsValidMessage(string from, string subject, string to, string body)
{
Regex chk = new Regex(@"(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})");
if (!chk.IsMatch(from))
{
return false;
}
if (!chk.IsMatch(to))
{
return false;
}
if (!string.IsNullOrEmpty(subject))
{
return false;
}
if (!string.IsNullOrEmpty(body))
{
return false;
}
else
{
return true;
}
}
#endregion Validation
}
任何建议将不胜感激,因此提前非常感谢您的所有 cmets!
注意:在这种特殊情况下实现 Enterprise Library 的Validation Application Block 是否方便?
【问题讨论】:
-
作为旁注,您使用 ArgumentException 错误 - 第二个参数是一个 string 应该是参数的 name无效的。相反,您在那里传递参数的值。你应该这样做:
throw new ArgumentException("Invalid sender address: " + from, "from"); -
非常感谢 Pavel,我正在添加它!
-
新版本的代码将难以调试。在 IsValidMessage() 中,您可以在一行中检查所有条件。当您使用调试器单步执行代码时,您将如何找出哪个不满意?你可以这样写: if( string.IsNullOrEmpty(subject) ) { return false; } if( !string.IsNullOrEmpty(body)) { return false; } 然后创建一个 Regex 对象并再次检查一个条件,一旦条件不满足,立即返回 false。
标签: c# vb6 exception-handling com-interop