[英]C# How to reference an inherited class from a base class
I am trying to refernce an inherited class from a base class, here's an example of what I have:我正在尝试从基类引用继承的类,这是我所拥有的示例:
public class A
{
//Some methods Here
}
public class B : A
{
//Some More Methods
}
I also have a List<A>
of which I've added B
to, and I'm trying to access B
from.我还有一个
List<A>
,我已经将B
添加到其中,我正在尝试从中访问B
。 Is there a way I can get B
from the List<A>
I have?有没有办法从我拥有的
List<A>
获取B
?
If you have added B
instances to List<A>
you could cast back the item to 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
...
}
}
Alternatively you could use the OfType<T>
extension method in order to get a subset of all items in the list which are instances of B:或者,您可以使用
OfType<T>
扩展方法来获取列表中所有项目的子集,这些项目是 B 的实例:
List<A> items = ...
List<B> bItems = items.OfType<B>().ToList();
foreach (B item in bItems)
{
...
}
You could add a property of type A and provide a constructor to assign it.您可以添加类型 A 的属性并提供一个构造函数来分配它。 You can then assing an instance of type B to that property.
然后,您可以将类型 B 的实例分配给该属性。
public class A
{
public A Child{ get; private set; }
public A(){}
public A( A child )
{
this.Child = child;
}
}
Anyway.. are you really sure that strong parent/child relation is really needed?无论如何..你真的确定真的需要牢固的父子关系吗? I think you could avoid it and make everything clearer, but you should provide your real world example (or something closer to you real world usage) in order to help.
我认为您可以避免它并使一切更清晰,但您应该提供您的真实世界示例(或更接近您真实世界用法的东西)以提供帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.