我试图发送一封电子邮件,其中发件人和收件人电子邮件地址(以及主题和正文内容)根据提供给该方法的值发生更改。这可能是最好的代码本身的解释:c#开关中的变量范围
public void EmailNotification(int emailAction)
{
MailAddress to;
MailAddress from;
string subject;
string body;
switch (emailAction)
{
case 1:
// Comment approved
to = new MailAddress("[email protected]");
from = new MailAddress("[email protected]");
subject = "Comment approved";
body = @"The comment you posted has been approved";
break;
case 2:
// Comment rejected
to = new MailAddress("[email protected]");
from = new MailAddress("[email protected]");
subject = "Comment rejected";
body = @"The comment you posted has been rejected";
break;
}
MailMessage message = new MailMessage(from, to);
message.Subject = subject;
message.Body = body;
SmtpClient client = new SmtpClient();
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in EmailNotification: {0}", ex.ToString());
}
}
所以问题是,由于范围与交换机的工作方式,对,发件人,主题等值不开关以外的认可,即使我已经在开关外面宣布了它们(可能是错误的?)。
我是一个.NET新手,所以任何有关如何完成这种事情的建议都将不胜感激。
难道你不能在交换机之前声明'MailMessage'对象,然后使用'message.To = new MailAddress(“....”);'在交换机内部吗? – dtsg