如果我有两个这样的列表:
IEnumerable<Student> students;
IEnumerable<Teacher> teachers;
我编写了一个方法,将学生列表导出到XML文件并执行
IEnumerable<Student>
作为输入。
有没有办法可以传递任何一个列表并让方法导出数据,而不必担心它是学生列表或教师列表?
答案 0 :(得分:2)
列表中的每个项目都需要知道如何导出自己。您需要让每个项目实现一个具有IExportable
方法的Export
接口。然后,您可以创建一个方法,例如:
public static void ExportAll(IEnumerable<IExportable> sequence)
{
//...
}
然后,您可以传递任何知道如何导出自身的类型的列表。
IExportable
可能最终为您ISerializable
,除非您打算使用其他方式导出项目。
答案 1 :(得分:1)
从基本抽象类继承,适用于序列化。
public abstract class Person
{
// your code goes here
// public string FirstName { get; set; }
// public string LastName { get; set; }
}
public class Student : Person
{
// your code goes here
}
public class Teacher : Person
{
// your code goes here
}
public void Export(IEnumerable<Person> persons)
{
// your code goes here
}
答案 2 :(得分:0)
在Student和Teacher上实现IPerson接口。然后更改XML导出方法以接受IEnumerable。 IPerson接口将具有检索XML导出数据所需的方法。