通过(列)名称而不是硬编码索引获取相关的ListViewSubItem?

时间:2016-02-11 14:10:04

标签: c# winforms listview listviewitem

我有一个ListViewItem 扩展方法包装器,它通过索引(硬编码)获取相关的SubItem引用,我想知道是否有方法来获取它不要硬编码索引号。

public class ListViewExtensionsLogic : IListViewExtensionsLogic
{
    public ListViewItem.ListViewSubItem GetUserIdSubitem(ListViewItem lvi)
    {
        return lvi.SubItems[1]; // I want to get it by not hard-coding it
    }
}

public static class ListViewExtensionMethods
{
        private static IListViewExtensionsLogic _listviewExtensionsLogic;

        static ListViewExtensionMethods()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<ListViewExtensionsLogic>().As<IListViewExtensionsLogic>();

            var container = builder.Build();
            container.BeginLifetimeScope();

            _listviewExtensionsLogic = container.Resolve<IListViewExtensionsLogic>();
        }

        public static ListViewItem.ListViewSubItem GetUserIdSubItem(this ListViewItem lvi)
        {
            return _listviewExtensionsLogic.GetUserIdSubitem(lvi);
        }
}

像这样使用:

        private void InitializeFollowers()
        {
            if (lvFollowList.Items.Count > 0)
            {
                foreach (ListViewItem lvi in lvFollowList.Items)
                {
                    if (!String.IsNullOrEmpty(lvi.GetUserIdSubItem().Text))
                    {
                        // Do something here
                    }
                }
            }
        }

1 个答案:

答案 0 :(得分:0)

为什么不将索引以及参数传递给方法,如下所示

public ListViewItem.ListViewSubItem GetUserIdSubitem(ListViewItem lvi, int index)
{
    return lvi.SubItems[index];
}