[英]C# - with a reference to a base class, how can I access a property of the inherited class if I know that my reference is to the inherited class?
[英]C# How to reference an inherited class from a base class
我正在尝试从基类引用继承的类,这是我所拥有的示例:
public class A
{
//Some methods Here
}
public class B : A
{
//Some More Methods
}
我还有一个List<A>
,我已经将B
添加到其中,我正在尝试从中访问B
。 有没有办法从我拥有的List<A>
获取B
?
如果您已将B
实例添加到List<A>
,则可以将项目回滚到B
:
List<A> items = ...
foreach (A item in items)
{
// Check if the current item is an instance of B
B b = item as B;
if (b != null)
{
// The current item is instance of B and you can use its members here
...
}
}
或者,您可以使用OfType<T>
扩展方法来获取列表中所有项目的子集,这些项目是 B 的实例:
List<A> items = ...
List<B> bItems = items.OfType<B>().ToList();
foreach (B item in bItems)
{
...
}
您可以添加类型 A 的属性并提供一个构造函数来分配它。 然后,您可以将类型 B 的实例分配给该属性。
public class A
{
public A Child{ get; private set; }
public A(){}
public A( A child )
{
this.Child = child;
}
}
无论如何..你真的确定真的需要牢固的父子关系吗? 我认为您可以避免它并使一切更清晰,但您应该提供您的真实世界示例(或更接近您真实世界用法的东西)以提供帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.