将对象转换为右类型

时间:2012-05-05 17:02:37

标签: c# .net oop class interface

我没什么问题。 在我的代码的第一个方法中,我已经将关于学生的数据从txt文件加载到List集合。有更多类型的学生(小学生,中学生,HightSchoolStudent,UniversityStudent,ExternStudent等课程......) 现在,在其他方法中我想将每种学生保存到不同的目录。我的问题是,我在该界面的一个集合中拥有所有对象。我现在怎么能区分或者我应该做些什么来区分所有类型的学生?请帮忙。

3 个答案:

答案 0 :(得分: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)
  {

    ...
  }
}

答案 1 :(得分:1)

查看c#中的is keyword

示例:

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

答案 2 :(得分:1)

您可以先从集合中获取所有学生类型,然后按类型将其保存到最终位置。这里给出的解决方案没有使用is或OfType&lt;&gt; LINQ方法,因为如果要将Students,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