1

我有小问题。在我的代码的第一种方法中,我已将有关学生的数据从 txt 文件加载到列表集合中。有更多类型的学生(PrimaryStudent、SecondaryStudent、HightSchoolStudent、UniversityStudent、ExternStudent 等类)现在,在其他方法中,我想将每种学生保存到不同的目录中。我的问题是我在该界面的一个集合中拥有所有对象。现在我该如何区分或应该如何区分所有类型的学生?请帮忙。

4

3 回答 3

2

如果您的列表是通用的,即List<Student>您可以执行以下操作:

List<PrimaryStudent> primaryStudents = myStudentList.OfType<PrimaryStudent>().ToList();

如果您的列表不是通用的,您可以像这样将它们分开:

foreach(var s in myStudentList)
{
  if(s is PrimaryStudent)
  { 

    // add to PrimaryStudents list
  }
  else if(s is SecondaryStudent)
  {

    ...
  }
}
于 2012-05-05T17:09:46.730 回答
1

看看c#中的is关键字

例子:

List<IStudent> students = new List<IStudent>();

students.Add(new PrimaryStudent());
students.Add(new SecondaryStudent());
students.Add(new HightSchoolStudent());

foreach (IStudent student in students)
{
    if (student is PrimaryStudent)
    {
        Console.WriteLine("This was a PrimaryStudent");
    }
    else if (student is SecondaryStudent)
    {
        Console.WriteLine("This was a SecondaryStudent");
    }
    else if (student is HightSchoolStudent)
    {
        Console.WriteLine("This was a HightSchoolStudent");
    }
}

Console.Read();

输出:

This was a PrimaryStudent
This was a SecondaryStudent
This was a HightSchoolStudent
于 2012-05-05T17:14:13.457 回答
1

您可以先从集合中获取所有学生类型,然后按类型将它们保存到最终位置。此处介绍的解决方案没有使用 is 或 OfType<> LINQ 方法,因为如果您想将 Student、PrimaryStudents 和 SecondaryStudents 存储在不同的文件夹中,这些运算符确实无法正常工作。

换句话说,如果您想以不同的方式处理基类的实例(例如保存到不同的文件夹),您需要放弃 OfType 和 is 运算符,但直接检查类型。

class Student { }
class PrimaryStudent : Student { }
class SecondaryStudent : Student { }

private void Run()
{
    var students = new List<Student> { new PrimaryStudent(), new PrimaryStudent(), new SecondaryStudent(), new Student() };
    Save(@"C:\University", students);
}

private void Save(string basePath, List<Student> students)
{
    foreach (var groupByType in students.ToLookup(s=>s.GetType()))
    {
        var studentsOfType = groupByType.Key;
        string path = Path.Combine(basePath, studentsOfType.Name);
        Console.WriteLine("Saving {0} students of type {1} to {2}", groupByType.Count(), studentsOfType.Name, path);
    }

}

Saving 2 students of type PrimaryStudent to C:\University\PrimaryStudent
Saving 1 students of type SecondaryStudent to C:\University\SecondaryStudent
Saving 1 students of type Student to C:\University\Student
于 2012-05-05T17:16:56.470 回答