【问题标题】:Checked items CheckedListBox with Object Collection带有对象集合的已检查项目 CheckedListBox
【发布时间】:2013-12-31 04:56:35
【问题描述】:

我有checkedlistbox 使用我的通用列表绑定。我需要根据价值检查项目。当我使用对象集合绑定时,我需要转换对象并检查 id。为此,我使用了以下循环,并且成功了

if (currentDeliveryNote.Quotations != null)
{
      foreach (QuotationBase item in currentDeliveryNote.Quotations)
      {
           for (int i = 0; i < chklstQuotation.Items.Count; i++)
           {
                if (((QuotationBase)chklstQuotation.Items[i]).ID == item.ID)
                {
                     chklstQuotation.SetItemChecked(i, true);
                }
           }
      }
}

现在同样的概念也适用于所有其他页面。但唯一的区别是对象名称不同。例如:在此页面中,这是QuotationBase。对于下一页,这是DeliveryNote,另一个是Invoice等。

那么我如何编写通用扩展方法来检查项目。所有对象都有 ID 属性,用于与列表进行比较以进行检查。

【问题讨论】:

  • 你有没有 Quotationbase、DeveliveryNote 和 Invoice 的基类以及 ID 的类型。

标签: c# extension-methods generic-list generic-collections


【解决方案1】:

你需要将你的 ID 属性放在一个接口上,然后你就可以使用泛型了:

public static void CheckItems<T>(this IEnumerable<T> items, CheckList checkList) where T : IIdentifiable
{
    if (items != null)
    {
        foreach (T item in items)
        {
           for (int i = 0; i < checkList.Items.Count; i++)
           {
                if (((T)checkList.Items[i]).ID == item.ID)
                {
                     checkList.SetItemChecked(i, true);
                }
           }
        }
    }
}

还有:

public interface IIdentifiable
{
    string ID { get; }
}

public class Quotationbase : IIdentifiable
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多