接受委托功能的扩展方法

时间:2012-06-06 13:14:20

标签: c# delegates extension-methods

我仍然试图绕过委托函数和扩展方法。我为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();
    }
}

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

myDropDownList.populateDropDownList(getDropDownDataSource());

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);
}

2 个答案:

答案 0 :(得分:6)

调用时,您应该在()之后移除getDropDownDataSource

myDropDownList.populateDropDownList(getDropDownDataSource);

编辑:方法组可以隐式转换为具有兼容签名的代理。在这种情况下,getDropDownDataSource匹配Func<IOrderedEnumerable<KeyValuePair<string,string>>>的签名,因此编译器会为您应用转换,从而有效地执行

Func<IOrderedEnumerable<KeyValuePair<string,string>>> func = getDropDownDataSource;
myDropDownList.populateDropDownList(func);

答案 1 :(得分:0)

是的,在myDropDownList.populateDropDownList(getDropDownDataSource());getDropDownDataSource(),您正在呼叫IOrderedEnumerable<KeyValuePair<string,string>>,后者会重新IOrderedEnumerable<KeyValuePair<string,string>>。所以,编译器说你不能将myDropDownList.populateDropDownList(getDropDownDataSource);转换为Func。要传递Func,你可以删除括号,以便传递像myDropDownList.populateDropDownList(() => { 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); } 这样的指针,或者你可以直接传递数据源代码:

{{1}}

但这有点难看。 : - )