简体   繁体   English

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

[英]How to access a derived class field from the base class

I created a derived class from ComboBoxItem in my Class Library. 我从类库中的ComboBoxItem创建了派生类。

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

And I assign each of this CustomComboxBoxItem into a ComboxBox 然后将每个CustomComboxBoxItem分配到ComboxBox中

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

            ComboBoxControl.Items.Add(BusinessNameItem);
        }

My question now is how can I access to the SupplierID from other form? 我现在的问题是如何从其他形式访问SupplierID?

Cast the ComboBoxItem to CustomComboBoxItem 将ComboBoxItem强制转换为CustomComboBoxItem

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

You can also do it in a foreach loop. 您也可以在foreach循环中执行此操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM