将覆盖的成员更改为异步 [英] Change overridden member to async
问题描述
我正在重写基类库中的方法.但是,在我的重写实现中,我正在使用新的HttpClient,它全部基于异步方法.因此,我必须将我的方法标记为异步,这意味着我需要将方法的返回参数从字符串更改为Task.但是,编译器给出了一个错误:返回类型必须为'string'才能匹配被重写的成员...."
I am overriding a method in a base class library. However, inside my overridden implementation I am using the new HttpClient which is all based on async methods. I therefore have to mark my method as async, which means that I need to change the return parameter of the method from string to Task. The compiler however gives an error: "The return type must be 'string' to match overridden member ...."
public class BaseClass
{
public virtual string GetName()
{
...
}
}
public class MyClass : BaseClass
{
public override async Task<string> GetName()
{
HttpClient httpClient = new HttpClient();
var response = await httpClient.GetAsync("");
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
return await responseContent.ReadAsStringAsync();
}
return null;
}
}
当然,显而易见的解决方案是将BaseClass中的GetName()的返回类型更改为Task< string> ;,但是我无法控制BaseClass,因为它是一个外部库;
Of course the obvious solution would be to change the return type of GetName() in BaseClass to Task<string>, but I have no control over BaseClass as it is an external library;
我当前的解决方案是以同步方式使用HttpClient类,即如下更改MyClass:
My current solution is to use the HttpClient classes in a synchronous fashion, i.e. change MyClass as follows:
public class MyClass : BaseClass
{
public override string GetName()
{
HttpClient httpClient = new HttpClient();
var response = httpClient.GetAsync("");
if (response.Result.IsSuccessStatusCode)
{
var responseContent = response.Result.Content;
return responseContent.ReadAsStringAsync()
.Result;
}
return null;
}
}
还有其他方法吗?
推荐答案
不幸的是,这里没有一个好的解决方案.没有办法用异步方法覆盖非异步方法.我认为您最好的选择是拥有一个 async
非重写方法,并从非异步方法调用该方法:
Unfortunately there isn't a good solution here. There is no way to override
a non-async method with an async one. I think your best bet is to have an async
non-override method and call into that from the non-async one:
public class MyClass : BaseClass
{
public override string GetName()
{
return GetNameAsync().Value;
}
public async Task<string> GetNameAsync()
{
...
}
}
请注意,这可能会导致问题.如果原始代码不希望执行任何 async
代码,则引入此模式可能会超出预期.如果可能的话,我会避免.
Note that this can cause problems though. If the original code didn't expect for any async
code to be executing introducing this pattern could break expectations. I would avoid it if possible.
这篇关于将覆盖的成员更改为异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!