如何将接口转换为正确的类? [英] How to convert interface to right class?

查看:65
本文介绍了如何将接口转换为正确的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好.我没什么问题
在我的代码的第一种方法中,我已将来自学生的数据从TXT文件加载到List<Student>集合中.学生的类型更多(班级PrimaryStudentSecondaryStudentHightSchoolStudentUniversityStudentExternStudent等).
现在,在另一种方法中,我想将每种Student保存到不同的目录.我的问题在于,我在该接口的一个集合中拥有所有对象.现在我该如何区分或应该怎么区分所有类型的学生?请帮忙.

Hi all. I have little problem.
In first method of my code I''ve loaded data about students from TXT file to List<Student> collection. There are more types of students (classes PrimaryStudent, SecondaryStudent, HightSchoolStudent, UniversityStudent, ExternStudent etc...)
Now, in other method I want to save every kind of Student to different directory. My problem is in that I have all objects in one collection in that interface. How can now I differentiate or what should I do to differentiate all types of students? Please help.

推荐答案

有两种选择.
There are two alternatives.

  1. 如果可以在类中引入method or property,则在Student 类中声明abstract or virtual方法或属性,并在派生类中声明override it,以返回适当的目录来保存该类,该目录可以用于保存.
  2. 对照Students的类检查对象,然后将其保存到不同的目录,如下所示.
  3. 这里展示了我使用Console.WriteLine的想法.该字符串可用于使用适当的代码保存到具有该名称的目录中.

  1. If a method or property can be introduced in the classes, then declare an abstract or virtual method or property in the Student class and override it in the derived classes to return an appropriate directory to save that class, which can be used for saving.
  2. Check the object against the classes of Students and save to different directories accordingly as shown below.
  3. Here to demonstrate the idea I have used Console.WriteLine. The string can be used for saving to a directory with that name using appropriate code.
void Main()
{
    List<Student> students = new List<Student>();
    students.Add(new PrimaryStudent());
    students.Add(new SecondaryStudent());

    //Alternative 1 If a method or property can be introduced
    //in the Derived classes
    students.ForEach(s => Console.WriteLine (s.GetDirectoryToSave()));

    //Alternative 2
    students.ForEach(s => {
        if (s is PrimaryStudent)
            Console.WriteLine (@"C:\PrimaryStudent");
        else if (s is SecondaryStudent)
            Console.WriteLine(@"C:\SecondaryStudent");

    });
}

public abstract class Student {
    public abstract string GetDirectoryToSave();

}

public class PrimaryStudent : Student {
    public override string GetDirectoryToSave(){
        return @"C:\PrimaryStudent";
    }
}
public class SecondaryStudent : Student {
    public override string GetDirectoryToSave(){
        return @"C:\SecondaryStudent";
    }
}


这篇关于如何将接口转换为正确的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆