如何将委托指向扩展方法

时间:2018-02-28 03:42:39

标签: c# delegates extension-methods

public class UITestCtrl
{

}

public static class Ext
{
    public static void FindElement(this UITestCtrl clas)
    {
    }
}

public class Brwsr : UITestCtrl
{
    public void FindElement()
    {
    }
}

现在,我正在尝试将委托指向扩展方法

private delegate void MyDell_();
MyDell_ dell = new MyDell_(Ext.FindElement());

我收到错误:

  

错误CS7036没有给出对应的参数   所需的正式参数' clas' ' Ext.FindElement(UITestCtrl)'

由于

1 个答案:

答案 0 :(得分:2)

// Your extension method is simply a static method taking one parameter and returning void, 
// so an action is appropriate delegate signature:
Action<UITestCtrl> dell = Ext.FindElement;

UITestCtrl control = new UITestCtrl();

dell(control);// calling the extension method via the assigned delegate, passing the one parameter

这是一个控制台应用程序,而不是UITestCtrl我使用了List:

static class Ext
{
    public static void FindElement(List<string> test)
    {
        test.Add("blah");
    }
}


class Program
{
    static void Main(string[] args)
    {
        Action<List<string>> dell = Ext.FindElement;

        var control = new List<string>();
        dell(control);// calling the extension method via the assigned delegate

    }
}