【问题标题】:c# ambiguous invocation implement and explict interface implementation时间:2018-01-10 标签:c#ambiguous invocation implement和explicit interface implementation
【发布时间】:2018-05-10 16:31:13
【问题描述】:

我有一个问题。我有一个类和接口,所以在类中我有 3 个看起来相似的方法,它们是:

    public CurrentsFlagAnalysis GetCurrentsFlag(DateTime startDateTime, DateTime endDateTime)
    {
        //some code
    }

    CurrentsFlagAnalysis ICurrentService<CurrentsFlagAnalysis>.GetCurrentsFlag(DateTime startDateTime, DateTime endDateTime, byte id)
    {
        //some code
    }

    List<CurrentsFlagAnalysis> ICurrentService<List<CurrentsFlagAnalysis>>.GetCurrentsFlag(DateTime startDateTime, DateTime endDateTime, byte id)
    {
        //some cone
    }

界面如下:

public interface ICurrentService <out TCurrent>
{
    TCurrent GetCurrentsFlag(DateTime startDateTime, DateTime endDateTime, byte id);

    CurrentsFlagAnalysis GetCurrentsFlag(DateTime startDateTime, DateTime endDateTime);
}

想法是使用这两个具有相同名称和相同参数但返回类型不同的方法,类似于重载,但是当我调用此方法时遇到了问题,例如:

    public Task<List<CurrentsFlagAnalysis>> GetCurrentsFlagAsync(DateTime startDateTime, DateTime endDateTime, byte id)
    {
        return Task.Run(() => GetCurrentsFlag(startDateTime, endDateTime, id));
    }

从编译时间开始:

错误 CS1501:方法 'GetCurrentsFlag' 没有重载需要 3 个参数

Visual Studio 向我发送了一条不明确的调用和可能的参数 null 异常的消息;

我得到了模棱两可的调用实现错误,我知道我应该使用某种显式实现,但不知道要咬它。

另一件事是这个东西是安全的,我应该只是重命名方法而忘记这个想法。

【问题讨论】:

  • 请您提供minimal reproducible example 并附上确切的错误消息?
  • 强制转换 this 以访问显式实现:((ICurrentService&lt;CurrentsFlagAnalysis&gt;)this).GetCurrentsFlag(...)

标签: c#


【解决方案1】:

即使在同一个类中,一旦将方法设为显式接口实现,就必须通过对接口的引用来调用它们:

return Task.Run(() => ((ICurrentService<CurrentsFlagAnalysis>)this).GetCurrentsFlag(
                                                               startDateTime, 
                                                               endDateTime, 
                                                               id));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 2015-02-05
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 2012-12-24
    • 2012-09-18
    相关资源
    最近更新 更多