【问题标题】:Convert object to right type将对象转换为正确的类型
【发布时间】:2012-05-14 21:31:23
【问题描述】:

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

【问题讨论】:

  • 您使用的是通用列表 吗?
  • 我正在寻找解决方案。

标签: c# .net oop class interface


【解决方案1】:

如果您的列表是通用的,即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)
  {

    ...
  }
}

【讨论】:

  • 如果您还想存储普通学生,OfType 不起作用,因为 OfType 不仅会返回学生,还会返回 Primary 和 SecondaryStudents。 OfType LINQ 运算符也有同样的问题。看看下面我的解决方案如何以安全的方式完成。
【解决方案2】:

看看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

【讨论】:

  • is 关键字仅在您不想存储作为中小学生基类的常规学生时才有效。
  • 如果你把 if 语句放在所有其他 if 语句的下面,它会起作用。
  • 确实如此,但这段代码很难维护和扩展。我不想每次都为新的学生类型编写额外的代码。我的通用解决方案不需要知道存在哪些学生类型。它只是按类型对它们进行分组。
【解决方案3】:

您可以先从集合中获取所有学生类型,然后按类型将它们保存到最终位置。此处介绍的解决方案没有使用 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

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    • 2012-01-16
    相关资源
    最近更新 更多