代码之家  ›  专栏  ›  技术社区  ›  ThePGtipsy

丢弃参数c中的对象类型#

  •  0
  • ThePGtipsy  · 技术社区  · 13 年前

    这是我遇到问题的代码部分;

    List<People> people = new List<People>();

    其中填充了3种不同类型的对象,所有这些对象都源自People类;

    people.Add(new Student(constructorarguments);
    people.Add(new AcademicStaff(constructorarguments);
    people.Add(new AdministrativeStaff(constructorarguments);
    

    这就是给我带来问题的代码;

    private void studentCheckbox_CheckedChanged(object sender, EventArgs e)
    {
        if (studentCheckbox.CheckState == CheckState.Checked)
        {
            foreach (Student student in people)
            {
                if (student.Compare(SearchTextBox.Text) == 0)
                {
                    resultsListBox.Items.Add(student.Forename);
                }
            }
        }
        else
        {}
    }
    

    它使用的是一个windows窗体,正如您可以从CheckState代码中看到的那样。但我遇到的问题是,这并没有限制与学生的比较。它试图超越学生,试图把教职员工塑造成学生,这就是我的项目的错误所在。在过去的几个小时里,我一直在为此而挣扎,没有任何回旋余地,任何帮助都将不胜感激!

    我不认为问题出在表格或课程本身,但我不知道为什么它试图转移到学术人员身上,而我把它限制在学生类型

    3 回复  |  直到 13 年前
        1
  •  2
  •   Dima    13 年前

    这是预期的行为,编译器枚举您的集合并隐式将每个项强制转换为 Student 类型
    如果只想循环 Students 你应该过滤你的 people 先收集 OfType<>() :

    foreach(var student in people.OfType<Student>())
    {
      ..
    }
    
        2
  •  1
  •   OopsUser    13 年前

    你不能在有人的列表上使用“学生”类型进行迭代,这段代码不应该编译。 您需要迭代类似的内容:

    foreach (People person in people)
    

    如果你想把现在的人选为学生,你应该写:

    Student s = person as Student;
    

    然后你就可以访问学生的方法了。

        3
  •  0
  •   Casperah    13 年前

    您可以使用linq方法OfType():

    private void studentCheckbox_CheckedChanged(object sender, EventArgs e)
    {
        if (studentCheckbox.CheckState == CheckState.Checked)
        {
            foreach (Student student in people.OfType<Student>())
            {
                if (student.Compare(SearchTextBox.Text) == 0)
                {
                    resultsListBox.Items.Add(student.Forename);
                }
            }
        }
        else
        {}
    }
    

    希望这能帮助你的探索。