【问题标题】:Returns void, a return keyword must not be followed by an object expression C# [closed]返回void,return关键字后面不能跟对象表达式C# [关闭]
【发布时间】:2017-01-30 15:56:03
【问题描述】:

我想在 C# ASP.NET 中发送电子邮件,问题是我将此错误标记为“返回 void,return 关键字后面不能跟对象表达式”。在这两个"return" 中都标记了相同的错误,这是什么?

 try
        {
            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
            mail.From = new MailAddress("email@gmail.com", "jhon", Encoding.UTF8);
             mail.Subject = "test email";
            mail.Body = "test email c#";
            mail.To.Add("michael@hotmail.com");
            SmtpServer.Port = 587; 
            SmtpServer.Credentials = new System.Net.NetworkCredential("email@gmail.com", "password");
            SmtpServer.EnableSsl = true;
            SmtpServer.Send(mail);
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }

【问题讨论】:

标签: c# asp.net return


【解决方案1】:

此错误消息意味着您的方法的返回类型是 void,而您的代码暗示您的方法应该返回 true 以表示成功发送的电子邮件,或 false 表示失败。

将方法的返回类型更改为bool 应该可以解决这个问题。但是,更好的方法是保留方法void,并抛出一个自定义异常,指示发送电子邮件的尝试不成功:

public class SendMailException : Exception {
    public SendMailException(Exception cause) : base(cause) {
    }
}
...
try {
    SmtpServer.Send(mail);
    // return true is removed
} catch (Exception cause) {
    throw new SendMailException(cause);
    // return false is removed
}

【讨论】:

  • 另外,如果任何时候的意图只是在条件发生时中断代码,而不是抛出错误,则在方法类型为void 时使用return;。跨度>
【解决方案2】:

我认为您的函数被定义为 void,并且您正在返回一个布尔值,请尝试更改预期为 bool 的返回值,如下所示:

bool myFunction(){

而不是

void myFunction(){

【讨论】:

    猜你喜欢
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    • 2013-06-04
    相关资源
    最近更新 更多