stackoverflow 社区您好!
我们开始吧!
我有一个小类人
:
class Person
{
public string name { get; set; }
}
它有一个后代Employee
:
class Employee : Person
{
public int salary { get; set; }
}
第二个后代是Guest
:
class Guest: Person
{
public int id { get; set; }
}
好的!看起来不错:)
现在我想在单个控件ListView
中显示所有员工或客人的列表
我为列表管理创建了一个类(确实有必要)PeopleList
:
class PeopleList
{
public List<Person> People { get; set; }
...
public void LoadListFromFile()
{
// Load logic
this.People = new List<?>(source);
}
}
你看到这个问号了吗?不?再看一下代码!
如何创建一个 List
实例,我可以使用我的类,如下所示:
// This instance with the list of Person objects
PeopleList list = new PeopleList();
foreach (Employee e in list.People)
{
Debug.WriteLine(e.salary.toString());
}
// This instance with the list of Guest objects
PeopleList list = new PeopleList();
foreach (Guest g in list.People)
{
Debug.WriteLine(g.id.toString());
}
P.S.我是 C# 新手,我认为我在架构方面有问题。也许你向我指出该模式可以解决我的问题。我真的需要你的帮助!谢谢!
最佳答案
我认为您正在寻找 System.Linq
库中的 OfType
:
foreach (Employee e in personList.OfType<Employee>())
{
Debug.WriteLine(e.salary.toString());
}
foreach (Guest g in personList.OfType<Guest>())
{
Debug.WriteLine(g.id.toString());
}
关于c# - 在C#中使用继承类作为实例List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18563890/