2017-03-16 121 views
-2

我正在收到(编译器错误)“错误CS0120非静态字段,方法或属性需要对象引用”。我的代码在下面提到。可以请任何人协助我如何解决这个问题。解决方案对于非静态字段,方法或属性,需要对象引用

private static Task<string> SendPasswordResetVerificationCode(string email) 
    { 
     string randomVerificationCode = new Random().Next(1000, 9999).ToString(CultureInfo.CurrentCulture); 

     ////send verification code to given email 
     if (email != null) 
     { 
      SendEmail(email, randomVerificationCode); 
      return Task.FromResult("VerificationCode Sent"); 
     } 

     return Task.FromResult("VerificationCode Sent"); 
    } 

    /// <summary> 
    /// Sends an email for verification code 
    /// </summary> 
    /// <param name="email">email address that will receive verification code</param> 
    /// <param name="verificationCode">verification code</param> 
    private void SendEmail(string email, string verificationCode) 
    { 
     Task.Run(() => 
     { 
      try 
      { 
        MailMessage mail = new MailMessage(); 
        SmtpClient smtpServer = new SmtpClient("smtp.gmail.com"); 
        mail.From = new MailAddress("[email protected]"); 
        mail.To.Add(email); 
        mail.IsBodyHtml = true; 
        mail.Subject = "Verification Code"; 
        mail.Body = verificationCode; 
        smtpServer.Port = 587; 

        smtpServer.UseDefaultCredentials = false; 
        smtpServer.EnableSsl = true; 
        smtpServer.Send(mail); 
        mail.Dispose(); 
      } 
      catch (Exception ex) 
      { 
       Utilities.Logging.LogManager.Write(ex); 
      } 
     }); 
    } 
+0

您需要发布更多信息...哪条线路会给您提供错误? – dana

+0

你的方法必须是静态的吗? 尝试删除静态访问修饰符。 – DaniDev

+0

你在哪里遇到异常?请检查您看到的异常并提供更多信息。 – STLDeveloper

回答

1

看看到您已经有,即,SendPasswordResetVerificationCodeSendEmail两种方法,其中SendEmail是实例方法,第一个是一个静态方法。现在看看错误消息。这很清楚,因为从静态方法调用SendEmail时,它说object reference is required for the nonstatic field, method, or property

所以修正方法也是快速简单的改变SendEmail。所以定义是这样的:

private static void SendEmail(string email, string verificationCode) 
{  
    // code here 
} 

注意:如果你没有任何具体的原因SendPasswordResetVerificationCode是静态意味着你可以删除签名静态以及不改变SendEmail的签名,但实际呼叫应与参考对象

相关问题