You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用微软示例排序ListView时遇'ListViewItemComparer'未找到错误求助

解决ListView排序时找不到ListViewItemComparer的问题

错误CS0246: 找不到类型或命名空间名称“ListViewItemComparer”的原因很直接:这个类不是.NET Framework或.NET的内置类,微软官方示例中默认你需要自行实现这个自定义的比较器类,只是文档里没有把它的代码直接放在主示例代码块中。

你需要在项目中添加以下ListViewItemComparer类的实现,它实现了IComparer接口,用于处理ListView按指定列和顺序排序的逻辑:

using System;
using System.Collections;
using System.Windows.Forms;

public class ListViewItemComparer : IComparer
{
    private int col;
    private SortOrder order;

    public ListViewItemComparer()
    {
        col = 0;
        order = SortOrder.Ascending;
    }

    public ListViewItemComparer(int column, SortOrder sortOrder)
    {
        col = column;
        order = sortOrder;
    }

    public int Compare(object x, object y)
    {
        int compareResult = String.Compare(
            ((ListViewItem)x).SubItems[col].Text,
            ((ListViewItem)y).SubItems[col].Text
        );

        // 根据排序顺序反转结果
        if (order == SortOrder.Descending)
            compareResult *= -1;

        return compareResult;
    }
}

注意事项:

  • 确保这个类和你的窗体类处于同一个命名空间下,或者在窗体类中添加对应的using引用(如果放在单独文件)。
  • 该类需要引用System.Collections命名空间,因为要实现IComparer接口。

添加完这个类后,你原有的排序代码就能正常运行,不会再出现找不到类型的错误。

内容的提问来源于stack exchange,提问作者John P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 21:34:56