如何从基类访问派生类字段

时间:2014-06-29 09:51:13

标签: c# oop derived-class

我在类库中从ComboBoxItem创建了一个派生类。

class CustomComboBoxItem : System.Windows.Controls.ComboBoxItem
{
    public string SupplierID { get; set; }
}

我将每个CustomComboxBoxItem分配到一个ComboxBox

while (dbReader.Read())
        {
            CustomComboBoxItem BusinessNameItem = new CustomComboBoxItem();
            BusinessNameItem.Content = dbReader["BusinessName"].ToString();
            BusinessNameItem.SupplierID = dbReader["SupplierID"].ToString();

            ComboBoxControl.Items.Add(BusinessNameItem);
        }

我现在的问题是如何从其他形式访问SupplierID?

1 个答案:

答案 0 :(得分:0)

将ComboBoxItem转换为CustomComboBoxItem

ComboBoxItem item = .....
CustomBoxItem castedItem  = item as CustomBoxItem;
if(null != castedItem)
{
    var supplier = castedItem.SupplierID;
}

您也可以在foreach循环中执行此操作。

foreach(var item in ComboBoxControl.Items)
{
    CustomBoxItem castedItem  = item as CustomBoxItem;
    if(null != castedItem)
    {
        var supplier = castedItem.SupplierID;
    }
}