【问题标题】:C# - Optional Async for InterfaceC# - 接口的可选异步
【发布时间】:2019-04-03 21:45:48
【问题描述】:

我有两个接口:

interface ICommandAsync : ICommand
{
    new Task Run(params string[] args);
}

interface ICommand
{
    string Name { get; }
    string Desc { get; }
    void Run(params string[] args);
}

“CommandWeather”没有实现接口成员“ICommand.Run(params string[])”。 'CommandWeather.Run(params string[])' 无法实现 'ICommand.Run(params string[])' 因为它没有匹配的返回类型 'void'。

这里是CommandWeather,或者违规类:

class CommandWeather : ICommandAsync
{
    public async Task Run(params string[] args)
    {
        //...
    }
}

我的问题是:如何创建一个可选异步的接口?我需要这些方法具有相同的名称,因为它们都将使用Run() 调用,并且只有少数ICommandICommandAsync 的实现实际上需要使用async。这意味着我获得了同步异步方法的绿线。

【问题讨论】:

  • 通常async方法有后缀Async,在你的情况下是RunAsync...或者使用显式接口实现...
  • @Johnny 问题在于我的命令是这样的:item.Key.Run(cmdTxt.Split(' ').Skip(1).ToArray()); 因为我从 yml 文件中解析所有命令,然后搜索具有该名称的适当文件。是否有可能让它调用RunAsync() 来获取实现它的命令?
  • @Johnny 澄清一下,cmdTxt 是用户输入的命令,item 是当前循环的命令的 <ICommand, List<String>> 条目(我循环遍历所有命令以找到具有正确的名称。列表适用于所有别名)。
  • 也许你可以使用显式接口并尝试将其转换为ICommandAsync,如果它失败调用同步一否则调用异步一...
  • @Johnny 听起来不错 ;) 谢谢。

标签: c# asynchronous interface


【解决方案1】:

至少明确地实现其中之一。

class CommandWeather : ICommandAsync
{
    public async Task Run(params string[] args)
    {
        //...
    }

    // Explicitly implement ICommand.Run
    void ICommand.Run(params string[] args)
    {
        //...
    }
}

这就是IEnumerator.Current 的实现方式,因为IEnumerator<T>.Current 是用new 声明的,并且是T 类型而不是object

@Johnny 提出了一个很好的观点,异步方法通常具有Async 后缀。这样也能解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 1970-01-01
    相关资源
    最近更新 更多