简体   繁体   English

C# 中没有合适的覆盖方法

[英]No suitable method to override in C#

I have the following method in my code, which takes a Guid as a parameter.我的代码中有以下方法,它以 Guid 作为参数。 I want to override this method with one that takes a string as a parameter:我想用一个将字符串作为参数的方法覆盖这个方法:

public class SendEmailApi: ISendEmailApi
{

     public async Task<EmailTemplate> GetTemplateByIdAsync(Guid templateId)
     {
         var response = await _emailClient.RequestAsync(EmailClient.Method.GET, urlPath: $"templates/{templateId}");

         return JsonConvert.DeserializeObject<EmailTemplate>(await response.Body.ReadAsStringAsync());
     }
}

However when I try to implement, I get the error that there is no suitable method to override.但是,当我尝试实现时,我得到了没有合适的方法来覆盖的错误。

public async override Task<EmailTemplate> GetTemplateByIdAsync(string templateId)
{
     var response = await _emailClient.RequestAsync(EmailClient.Method.GET, urlPath: $"templates/{templateId}");

     return JsonConvert.DeserializeObject<EmailTemplate>(await response.Body.ReadAsStringAsync());
}      

The interface looks like this:界面如下所示:

public interface ISendEmailApi
{
    Task<EmailTemplate> GetTemplateByIdAsync(Guid templateId);
}

I am relatively new to C# and .NET and any advice would be appreciated - I am sure I am missing something obvious?我对 C# 和 .NET 比较陌生,任何建议都将不胜感激 - 我确定我遗漏了一些明显的东西? Thanks谢谢

The other method you want is not an override , override means you're overriding a virtual method in the base class.您想要的另一种方法不是overrideoverride意味着您正在覆盖基础 class 中的virtual方法。 And you have no base class.而且您没有基础 class。

Remove the override keyword in your function and it will work as you want.删除 function 中的override关键字,它将按您的意愿工作。

The error is correct.错误是正确的。 In order to override an existing method it has to have the exact same signature as the method it is overriding.为了覆盖现有方法,它必须具有与其覆盖的方法完全相同的签名。 Since your method takes in a string it can't override a method that takes in a Guid.由于您的方法接受一个字符串,它不能覆盖一个接受 Guid 的方法。 Instead I think you want to overload the method ( Overloading and overriding .)相反,我认为您想重载该方法( Overloading 和 overriding 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM