Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#-接口的可选异步_C#_Asynchronous_Interface - Fatal编程技术网

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)
    {
        //...
    }
}