C#-接口的可选异步
我有两个接口:C#-接口的可选异步,c#,asynchronous,interface,C#,Asynchronous,Interface,我有两个接口: interface ICommandAsync : ICommand { new Task Run(params string[] args); } 及 “CommandWeather”未实现接口成员“ICommand.Run(参数字符串[])”CommandWeather.Run(params字符串[])无法实现“ICommand.Run(params字符串[])”,因为它没有匹配的返回类型“void” 以下是CommandWeather,或者是违规的类别: clas
interface ICommandAsync : ICommand
{
new Task Run(params string[] args);
}
及
“CommandWeather”未实现接口成员“ICommand.Run(参数字符串[])”CommandWeather.Run(params字符串[])无法实现“ICommand.Run(params字符串[])”,因为它没有匹配的返回类型“void”
以下是CommandWeather
,或者是违规的类别:
class CommandWeather : ICommandAsync
{
public async Task Run(params string[] args)
{
//...
}
}
我的问题是:如何创建可选异步的接口?我需要方法具有相同的名称,因为它们都将通过
Run()
调用,并且只有少数ICommand
或ICommandAsync
的实现实际需要使用async
。这意味着使用同步异步方法会得到绿线。明确实现其中至少一个方法
class CommandWeather : ICommandAsync
{
public async Task Run(params string[] args)
{
//...
}
// Explicitly implement ICommand.Run
void ICommand.Run(params string[] args)
{
//...
}
}
这就是IEnumerator.Current
的实现方式,因为IEnumerator.Current
是用new
声明的,属于T
类型,而不是object
@Johnny提出了一个很好的观点,异步方法通常有
async
后缀。这也可以解决问题。通常,async
方法的后缀是async,在您的例子中是RunAsync。。。或者使用显式接口实现…@Johnny这方面的问题是我使用如下命令:item.Key.Run(cmdTxt.Split(“”).Skip(1.ToArray())代码>因为我解析了yml文件中的所有命令,然后搜索具有该名称的适当文件。有没有可能让它调用RunAsync()
来实现这个功能呢?@Johnny要澄清的是,cmdTxt
是用户对命令的输入,item
是当前循环的命令的
项(我循环所有命令,以找到名称正确的命令。列表中列出了所有别名)。也许您可以使用显式接口,并尝试将其强制转换为ICommandAsync
,如果失败,则调用同步接口,否则调用异步接口…@Johnny听起来不错;)非常感谢。
class CommandWeather : ICommandAsync
{
public async Task Run(params string[] args)
{
//...
}
// Explicitly implement ICommand.Run
void ICommand.Run(params string[] args)
{
//...
}
}