如何在Dictionary中存储比较函数?

时间:2011-07-11 14:52:22

标签: c# function dictionary

我想通过使用密钥访问我的比较功能。这就是我尝试过的。我认为我的问题是我如何声明字典值的类型。

internal static int CompareUsersByEmail(MembershipUser a, MembershipUser b)
{
    // imagine null checking happening here.
    return string.Compare(a.Email, b.Email, true);
}

public static void Sort(List<MembershipUser> list, string expression) {

    // I can do this
    list.Sort(CompareUsersByEmail);

    // but not this
    Dictionary<string, Func<MembershipUser, MembershipUser, int>> compareFns;
    compareFns = new  Dictionary<string, Func<MembershipUser, MembershipUser, int>>();
    compareFns["Email"] = CompareUsersByEmail;
    list.Sort(compareFns[expression]); // where expression would be "Email"
}

这可能吗?

1 个答案:

答案 0 :(得分:1)

将字典类型更改为:

Dictionary<string, Comparison<MembershipUser>> compareFns;

我相信它会在没有其他变化的情况下发挥作用。方法组转换为Comparison<MembershipUser>仍然有效,现在您可以调用List<T>.Sort(Comparison<T>)