接受委托功能的扩展方法

bfl*_*mi3 1 c# extension-methods delegates

我仍然试图围绕委托函数和扩展方法.我已经创建了一个扩展方法DropDownList.我想在我的扩展方法中传递要调用的函数,但是我收到了一个错误Argument type 'IOrderedEnumerable<KeyValuePair<string,string>>' is not assignable to parameter type 'System.Func<IOrderedEnumerable<KeyValuePair<string,string>>>'

public static class DropDownListExtensions {
    public static void populateDropDownList(this DropDownList source, Func<IOrderedEnumerable<KeyValuePair<string, string>>> delegateAction) {
        source.DataValueField = "Key";
        source.DataTextField = "Value";
        source.DataSource = delegateAction;
        source.DataBind();
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样被召唤......

myDropDownList.populateDropDownList(getDropDownDataSource());
Run Code Online (Sandbox Code Playgroud)

getDropDownDataSource签名......

protected IOrderedEnumerable<KeyValuePair<string,string>> getDropDownDataSource() {
    StateInfoXmlDocument stateInfoXmlDocument = new StateInfoXmlDocument();
    string schoolTypeXmlPath = string.Format(STATE_AND_SCHOOL_TYPE_XML_PATH, StateOfInterest, SchoolType);
    var nodes = new List<XmlNode>(stateInfoXmlDocument.SelectNodes(schoolTypeXmlPath).Cast<XmlNode>());
    return nodes.Distinct().Select(x => new KeyValuePair<string, string>(x.Attributes["area"].Value, x.Attributes["area"].Value)).OrderBy(x => x.Key);
}
Run Code Online (Sandbox Code Playgroud)

Lee*_*Lee 6

你应该在调用时删除()after getDropDownDataSource:

myDropDownList.populateDropDownList(getDropDownDataSource);
Run Code Online (Sandbox Code Playgroud)

编辑:方法组可以隐式转换为具有兼容签名的委托.在这种情况下,getDropDownDataSource匹配签名,Func<IOrderedEnumerable<KeyValuePair<string,string>>>以便编译器为您应用转换,有效地执行

Func<IOrderedEnumerable<KeyValuePair<string,string>>> func = getDropDownDataSource;
myDropDownList.populateDropDownList(func);
Run Code Online (Sandbox Code Playgroud)