这个问题在这里已有答案:
我得到(编译器错误)“错误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("v@gmail.com");
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);
}
});
}
1 回答
看看你已经拥有的两种方法,即
SendPasswordResetVerificationCode
和SendEmail
,其中SendEmail是实例方法,第一种是静态方法 . 现在看一下错误信息 . 它很清楚,当你从静态方法调用SendEmail
时它会说object reference is required for the nonstatic field, method, or property
.所以修复是快速而简单的改变
SendEmail
作为静态方法 . 所以定义如下:注意:如果你没有任何特定的理由让
SendPasswordResetVerificationCode
成为静态意味着你也可以从签名中删除静态而不改变SendEmail
的签名,但实际的调用应该是一个引用对象