【问题标题】:IComparer does not implement interface member - Error CS0738 [closed]IComparer 未实现接口成员 - 错误 CS0738 [关闭]
【发布时间】:2021-01-23 01:10:45
【问题描述】:

我正在尝试使用以下代码通过它们的一个属性(.Transaction.topLeftX,一个整数)对两个对象进行排序,以创建一个在 Sort 方法中使用的比较器:

public class RespComp : IComparer<Kairos.Net.RecognizeImage>
{     
        public Kairos.Net.RecognizeImage Compare(Kairos.Net.RecognizeImage x, Kairos.Net.RecognizeImage y)
        {
            if (x.Transaction.topLeftX.CompareTo(y.Transaction.topLeftX) <= 0) return x;
               else return y;                      
        }
}

但是,我收到错误消息 Error CS0738 'RecogniseFacesKairos.RespComp' 没有实现接口成员 'IComparer.Compare(RecognizeImage, RecognizeImage)'。 “RecogniseFacesKairos.RespComp.Compare(RecognizeImage, RecognizeImage)”无法实现“IComparer.Compare(RecognizeImage, RecognizeImage)”,因为它没有匹配的返回类型“int”。

Sort方法中使用的比较器是否需要返回类型为int?

【问题讨论】:

  • 可以把方法的签名贴在接口里吗?
  • "因为它没有匹配的返回类型'int'"。是的,您的方法必须返回“int”。
  • because it does not have the matching return type of 'int'. 是的 - 这就是你需要做的。

标签: c# icomparer


【解决方案1】:

IComparer&lt;T&gt; 接口应该实现一个返回 int 比较的方法。 -1 小于,0 等于,1 大于。

查看您的代码,如果您只是比较左上角,您可能只需执行以下操作:

public int Compare(FooImage x, FooImage y) {
    return x.Transaction.topLeftX.CompareTo(y.Transaction.topLeftX);
}

【讨论】:

    【解决方案2】:

    通过以下代码实现按其中一个参数对对象进行排序的预期结果:

    ...
    Kairos.Net.KairosClient client = new Kairos.Net.KairosClient();
    client.ApplicationID = appId;
    client.ApplicationKey = appKey;
    Kairos.Net.RecognizeResponse resp = client.Recognize(...);
    
    RespComp SortImages = new RespComp();
    resp.Images.Sort(SortImages);
    ...
    
     public class RespComp : IComparer<Kairos.Net.RecognizeImage>
        {
            public int Compare(Kairos.Net.RecognizeImage x, Kairos.Net.RecognizeImage y)
            {
                return x.Transaction.topLeftX.CompareTo(y.Transaction.topLeftX);
            }
        }  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多