C# 无法声明接口“ async Task<myObject> MyMethod(Object myObj); ”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13049128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unable to declare Interface " async Task<myObject> MyMethod(Object myObj); "
提问by goodguys_activate
I'm unable to declare
我无法申报
interface IMyInterface
{
async Task<myObject> MyMethod(Object myObj);
}
The compiler tells me:
编译器告诉我:
- The modifier async isn't valid for this item
- The async modifier can only be used for methods that have a body
- 修饰符 async 对此项无效
- async 修饰符只能用于具有主体的方法
Is this something that should be implemented, or does the nature of async & await prohibit this from ever occurring?
这是应该实现的东西,还是 async & await 的性质禁止这种情况发生?
采纳答案by stuartd
Whether a method is implemented using async/await or not is an implementation detail. How the method should behave is a contract detail, which should be specified in the normal way.
Note that if you make the method return a
Taskor aTask<T>, it's more obvious that it's meant to be asynchronous, and will probably be hard to implement without being asynchronous.
一个方法是否使用 async/await 实现是一个实现细节。方法的行为方式是合同细节,应以正常方式指定。
请注意,如果您让方法返回 a
Task或 aTask<T>,则更明显的是它是异步的,如果不异步,可能很难实现。
回答by Roy Dictus
Whether or not your implementation is async, has no relevance to your interface. In other words, the interface cannot specify that a given method must be implemented in an asynchronous way.
您的实现是否是异步的,与您的界面无关。换句话说,接口不能指定给定的方法必须以异步方式实现。
Just take asyncout of your interface and it will compile; however, there is no way to enforce asynchronous implementation just by specifying an interface.
只需async取出您的界面,它就会编译;但是,没有办法仅通过指定接口来强制执行异步实现。
回答by Simon_Weaver
If you have an interface with two implementations (one that is truly async and the other that is synchronous) this is what it would look like for each implementation - with both returning a Task<bool>.
如果你的接口有两个实现(一个是真正异步的,另一个是同步的),这就是每个实现的样子——两者都返回一个Task<bool>.
public interface IUserManager
{
Task<bool> IsUserInRole(string roleName);
}
public class UserManager1 : IUserManager
{
public async Task<bool> IsUserInRole(string roleName)
{
return await _userManager.IsInRoleAsync(_profile.Id, roleName);
}
}
public class UserManager2 : IUserManager
{
public Task<bool> IsUserInRole(string roleName)
{
return Task.FromResult(Roles.IsUserInRole(roleName));
}
}
If it is a void method you need to return Task.CompletedTask;from the non async method
(I think .NET 4.5 and later)
如果它是一个 void 方法,您需要return Task.CompletedTask;从非异步方法(我认为 .NET 4.5 及更高版本)
See also : Return Task<bool> instantly
另请参阅:立即返回 Task<bool>

