委托参数

时间:2019-06-04 19:30:42

标签: c# delegates

我有一堆返回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));
    }

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

3 个答案:

答案 0 :(得分:3)

您需要传递一个delegate(这是一个知道如何调用方法的对象,即:它保存了方法的引用) 您所做的就是传递执行后得到的函数结果 GetTopNeighbour(c)返回一个List<GridTile>,您正在此处的代码中传递此返回值

AutoConnect(c, GetTopNeighbour(c));

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

AutoConnect(c, GetTopNeighbour);

请参阅这些This is a tutorialhere's another one

答案 1 :(得分:1)

您必须传递方法(或方法组)本身,而不是调用它:

AutoConnect(c, GetTopNeighbour);

答案 2 :(得分:1)

您将GetTopNeighbour(c)的结果(List<GridTile>)作为自动连接的参数。

相反,您希望将MethodGroup传递给委托,就像这样:

AutoConnect(c, GetTopNeighbour);