作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
如果我有这样的界面:
using System.Threading.Tasks;
...
public interface IFoo
{
Task doIt();
Task<bool> doItAndReturnStuff();
}
实现此接口(interface)的类之一恰好不需要异步方法,我该如何正确覆盖这些函数?
换句话说,如何正确返回包装在 Task 对象中的“void”和“bool”?
例如:
public class FooHappensToNotNeedAsync : IFoo
{
public override Task doIt()
{
// If I don't return anything here, I get
// error that not all code paths return a value.
// Can I just return null?
}
public override Task<bool> doItAndReturnStuff()
{
// If I want to return true, how to I do it?
// This doesn't work:
return true;
}
}
注意 - 我不能完全去除 Task 的东西,因为一些实现这个接口(interface)的类实际上是异步的。
谢谢
最佳答案
不清楚您要实现的目标,但一种方法(看起来最像“正常”代码)可能只是使它们成为异步方法:
public async Task DoIt()
{
// No-op
}
public async Task<bool> DoItAndReturnStuff()
{
return true;
}
没有任何 await
表达式,该方法无论如何都会同步完成。您将在每种方法上收到警告,但您可以使用 #pragma
仅针对这段代码禁用它。
或者 - 我想更简单的是不需要 #pragma
来禁用警告 - 将使用 Task.FromResult
:
public Task DoIt()
{
// Returns a Task<bool>, but that's okay - it's still a Task
return Task.FromResult(true);
}
public Task<bool> DoItAndReturnStuff()
{
return Task.FromResult(true);
}
关于c# - 异步编程和虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13524762/
我有一个特别的问题想要解决,我不确定是否可行,因为我找不到任何信息或正在完成的示例。基本上,我有: class ParentObject {}; class DerivedObject : publi
在我们的项目中,我们配置了虚 URL,以便用户可以在地址栏中输入虚 URL,这会将他们重定向到原始 URL。 例如: 如果用户输入'http://www.abc.com/partner ',它会将它们
我是一名优秀的程序员,十分优秀!