关于列表排序和委托&lambda表达式Func的东西

hax*_*mer 6 c#

List<bool> test = new List<bool>();
test.Sort(new Func<bool, bool, int>((b1, b2) => 1));
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

错误2参数1:无法从'System.Func'转换为'System.Collections.Generic.IComparer'

错误1'System.Collections.Generic.List.Sort(System.Collections.Generic.IComparer)'的最佳重载方法匹配有一些无效的参数

当我有

private int func(bool b1, bool b2)
{
    return 1;
}

private void something()
{
    List<bool> test = new List<bool>();
    test.Sort(func);
}
Run Code Online (Sandbox Code Playgroud)

它工作正常.他们不是一回事吗?

usr*_*usr 11

Func是错误的委托类型.您可以使用以下任一方法:

test.Sort((b1, b2) => 1);
test.Sort(new Comparison<bool>((b1, b2) => 1));
Run Code Online (Sandbox Code Playgroud)

  • 这是编译器比你更聪明的一个很好的例子(或者我们,因为我需要查看它).让它弄明白(通过在lambdas中隐式输入),而不是试图明确告诉它应该已经知道的东西. (2认同)