如何允许我将方法传递给 List.Sort()?
List<Stuff> list = new List<Stuff>();
list.Sort(StuffSortByName);
: StuffSortByName
声明:
private static int StuffSortByName(Stuff x, Stuff y)
{
...
}
令我惊讶的是我的代码编译并且有效。令人惊讶的是 Sort
没有重载采用方法:
所以我很幸运,因为我不想创建一个实现 IComparer 的整个对象,只是为了对东西进行排序。但就我的一生而言,我在编译时无法理解。
现在我想复制这个魔法。我想对 ListView 进行排序。但是您不对列表进行排序,而是通过它的 ListViewItemSorter
属性:
listView1.ListViewItemSorter = [IComparer]
再说一遍,我不想写整个对象,我只想传递本地方法(最好是非静态方法):
listView1.ListViewItemSorter = SortListView;
private static int SortListView(Object x, Object y)
{
....
}
现在当然不会编译,因为它没有意义。但是早期的语法也不应该编译 - 但它确实可以编译。
所以它给了我希望,我可以在这里拥有同样令人困惑的语法。
在第一种情况下如何允许我传递一个方法作为排序比较器,但在第二种情况下不允许?
List<Stuff> list = new List<Stuff>();
list.Sort(StuffSortByName);
with the StuffSortByName
declaration of:
private static int StuffSortByName(Stuff x, Stuff y)
{
...
}
What surprises me is that my code compiles and works. It's surprising that no overload of Sort
takes a method:
So i was fortunate, as i didn't want to have to create a whole object, that implements IComparer, just to sort stuff. But for the life of me i don't understand while it compiles.
And now i want to duplicate that magic. i want to sort a ListView. But you don't sort a listivew, you give a listview an IComparer
through it's ListViewItemSorter
property:
listView1.ListViewItemSorter = [IComparer]
And, again, i don't want to write a whole object, i just want to pass a local method (and ideally a non-static one):
listView1.ListViewItemSorter = SortListView;
private static int SortListView(Object x, Object y)
{
....
}
Now of course this doesn't compile because it makes no sense. But then the earlier syntax shouldn't compile either - but it does.
So it gives me hope that i can have the same confusing syntax here.
How was i allowed to pass a method as a sort comparer in the first case, but not in the second case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要回答您的第一个问题,可以传递方法名称的原因是因为
Comparison
是委托类型,这意味着它是表示方法签名的类型。有关详细信息,请参阅 MSDN。在您的情况下,您应该创建一个
IComparer
对象,或者让您的Stuff
对象实现IComparable
或IComparable
>(如果可能)。To answer your first question, the reason the method name can be passed is because
Comparison<T>
is a delegate type, meaning it is a type representing a method signature. See MSDN for details.In your case, you should either create an
IComparer
object or have yourStuff
object implementIComparable
orIComparable<T>
(if possible).我认为您只需使用此重载。它使用 比较
来自链接:
EDIT
那么
ListView
呢,正如您也注意到的那样,它实现了IComparer
而不Comparison
,因此您不能只将委托传递给它。I think you simply use this overload. which uses Comparison
From link:
EDIT
What about
ListView
, as you noticed too, it implementsIComparer
and notComparison
, so you can not just pass a delegate to it.