【发布时间】:2023-01-05 22:50:40
【问题描述】:
实际上所有这些类都在第三个库中定义,所以我无法更改它们。
=====================
我正在学习 C#,但遇到了一个问题。 假设我有一个父类和两个子类:
class ParentClass
{
....
};
class ChildA : ParentClass
{
public string name;
};
class ChildB : ParentClass
{
public string name;
};
ChildA 和 ChildB 类都具有属性 name,但 ParentClass 没有。
现在我需要将 ChildA 和 ChildB 存储在字典中,所以我写 Dictionary<string, ParentClass>。
但我无法获取名称,因为 ParentClass 没有此属性:
foreach (ParentClass pc in dict.Values)
{
// it works, but too verbose as I may have ChildC, ChildD...
if (pc is ChildA ca)
{
ca.name
}
if (pc is ChildB cb)
{
cb.name
}
// how can I get the name property at same time?
}
我该如何处理?
【问题讨论】:
-
您是否尝试过在父组件中添加 name 属性并将其从子组件中删除?
-
当父类不知道该属性并且您无法更改它时,除了向下转换为适当的 child.class 并在那里调用成员之外别无他法。
标签: c# inheritance