继承类列表列表框类名此时无效

本文关键字:列表 无效 继承 | 更新日期: 2023-09-27 18:25:04

我正在创建一个WinForms应用程序,我有一个数据源为ObservableCollection<ParentClass>的Listbox,我正在尝试基于该类的子类设置特定标签。我得到错误"类名在这一点上无效"。样本代码:

using System;    
public class Parent
{
    public Parent() { }
    public class ChildA : Parent
    {
        public ChildA() { }
    }
}
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        ObservableCollection<Parent> listBoxSource = 
               new ObservableCollection<Parent>();
        listBox.DataSource = listBoxSource;
    }
    private void customerListBox_SelectedIndexChanged(object sender, 
                 EventArgs e)
    {
        if (customerListBox.SelectedItem.GetType() ==
              Parent.ChildA) // <---Error Here
        {
            //Code Here
        }
    }    
}

有没有更好的方法可以根据元素的类型执行操作?

继承类列表列表框类名此时无效

更改此项:

 if (customerListBox.SelectedItem.GetType() == Parent.ChildA)

至:

 if (customerListBox.SelectedItem is Parent.ChildA)

或者正如你所做的:

 if (customerListBox.SelectedItem.GetType() == typeof(Parent.ChildA))

意识到使用运算符"is"避免检查对象是否为null。