1

我仍在尝试围绕委托函数和扩展方法。我为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);
}
4

2 回答 2

6

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

myDropDownList.populateDropDownList(getDropDownDataSource);

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

Func<IOrderedEnumerable<KeyValuePair<string,string>>> func = getDropDownDataSource;
myDropDownList.populateDropDownList(func);
于 2012-06-06T13:16:31.877 回答
0

是的,在myDropDownList.populateDropDownList(getDropDownDataSource());您调用的行getDropDownDataSource()中返回 a IOrderedEnumerable<KeyValuePair<string,string>>。所以,编译器说你不能转换IOrderedEnumerable<KeyValuePair<string,string>>为 Func。要传递 Func,您可以删除括号以便传递这样的指针myDropDownList.populateDropDownList(getDropDownDataSource);,也可以直接传递数据源代码:

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

但这有点难看。:-)

于 2012-06-06T13:20:53.760 回答