c# - 在C#中使用继承类作为实例List

标签 c# .net winforms design-patterns ilist

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/

相关文章:

c# - 在 MVC 中处理来自共享控件的事件

c# - 当我使用 Action<> 设置对象时,分配的对象始终为 null

.net - 如何使用统一 IoC 容器

c# - 检测具有相同 child 的实体

c# - ClickOnceInstall CefSharp Winforms 问题

c# - 为 Windows 窗体 C# 设置日期时间选择器的最小日期

c# - 刷新 Windows 窗体中的 DataGridView

c# - 我是否应该创建域对象的接口(interface)以在单元测试中隔离它们

c# - 如何从函数中检索输入

c# - ProgressBar 十进制值