【问题标题】:Delegate in parameter参数中的委托
【发布时间】:2019-06-04 19:30:42
【问题描述】:

我有一堆返回 GridTiles 列表的方法,例如 GetTopNeighbour。我希望能够使用 GetNeighboursHandler 委托作为参数将它们传递给 AutoConnect 方法。

    public delegate List<GridTile> GetNeighboursHandler(GridTile c);

    public List<GridTile> GetTopNeighbour(GridTile c)
    {
        //do stuff and return list
        return null;
    }
     public GridTile AutoConnect(GridTile c, GetNeighboursHandler del)
    {
        List<GridTile> tempList = del(c);

        // do stuff with the tempList
    }

    public void Test(GridTile c)
    {
        AutoConnect(c, GetTopNeighbour(c));
    }

在测试方法中,我收到错误:... 无法将 ...Generic.List... 转换为 GetNeighboursHandler。 我是否完全误解了代表的工作方式?

【问题讨论】:

    标签: c# delegates


    【解决方案1】:

    你需要传递一个delegate(这是一个知道如何调用方法的对象,即:它持有一个方法的引用) 您所做的是传递执行后获得的函数结果 GetTopNeighbour(c) 返回一个 List&lt;GridTile&gt;,您在此处的代码中传递此返回值

    AutoConnect(c, GetTopNeighbour(c));
    

    您应该将引用传递给该方法GetTopNeighbour

    AutoConnect(c, GetTopNeighbour);
    

    参考这些This is a tutorialhere's another one

    【讨论】:

      【解决方案2】:

      您必须传递方法(或者更确切地说,方法组)本身,而不是调用它:

      AutoConnect(c, GetTopNeighbour);
      

      【讨论】:

        【解决方案3】:

        您将 GetTopNeighbour(c) 的结果(即 List&lt;GridTile&gt;)作为参数传递给 AutoConnect。

        相反,您希望传递要转换为委托的 MethodGroup,如下所示:

        AutoConnect(c, GetTopNeighbour);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-12-25
          • 2016-08-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多