C# 关于列表排序和代表&;lambda表达式函数 List test=newlist(); 测试排序(新函数((b1,b2)=>1));
我错过了什么 错误2参数1:无法从“System.Func”转换为“System.Collections.Generic.IComparer” 错误1“System.Collections.Generic.List.Sort(System.Collections.Generic.IComparer)”的最佳重载方法匹配具有一些无效参数 当我有C# 关于列表排序和代表&;lambda表达式函数 List test=newlist(); 测试排序(新函数((b1,b2)=>1));,c#,C#,我错过了什么 错误2参数1:无法从“System.Func”转换为“System.Collections.Generic.IComparer” 错误1“System.Collections.Generic.List.Sort(System.Collections.Generic.IComparer)”的最佳重载方法匹配具有一些无效参数 当我有 List<bool> test = new List<bool>(); test.Sort(new Func<bool, b
List<bool> test = new List<bool>();
test.Sort(new Func<bool, bool, int>((b1, b2) => 1));
private int func(布尔b1,布尔b2)
{
返回1;
}
私人的
{
列表测试=新列表();
test.Sort(func);
}
它很好用。它们不是一回事吗?Func是错误的委托类型。您可以使用以下任一选项:
private int func(bool b1, bool b2)
{
return 1;
}
private void something()
{
List<bool> test = new List<bool>();
test.Sort(func);
}
test.Sort((b1,b2)=>1);
测试.排序(新的比较((b1,b2)=>1));
因为您需要传递一个系统。比较
,而不是函数
。放下新函数…
,它应该可以工作
test.Sort((b1, b2) => 1);
test.Sort(new Comparison<bool>((b1, b2) => 1));
您也可以尝试:
test.Sort((b1, b2) => !b1 && b2 ? -1 : b1 && !b2 ? +1 : 0);
删除新功能
var测试=新列表();
测试排序((a,b)=>1);
这是一个很好的例子,说明编译器比您(或我们)更聪明,因为我需要查找这一点。只是让它自己去弄清楚(通过lambdas中的隐式输入),而不是试图显式地告诉它应该知道的事情。这就是我的编码风格。它相当于List test=newlist()代码>我的意思是使用var test=newlist而不是List test=newlist()更好吗;它的风格。它们产生完全相同的IL。
test.Sort( delegate(bool b1,bool b2){return 1;});
var test = new List<bool>();
test.Sort((a, b) => 1);