C#如何从基类

时间:2016-08-22 15:14:57

标签: c# class inheritance access derived

我正在尝试从基类引用一个继承的类,这里是我所拥有的一个例子:

public class A
{
//Some methods Here
}
public class B : A
{
//Some More Methods
}

我还有一个List<A>我已添加B,我试图访问B。有没有办法从我B获得List<A>

2 个答案:

答案 0 :(得分:2)

如果您已将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)
{
    ...
}

答案 1 :(得分:0)

您可以添加A类型的属性并提供构造函数来分配它。然后,您可以将类型B的实例分配给该属性。

public class A
{
      public A Child{ get; private set; }

      public A(){}

      public A( A child )
      { 
          this.Child = child;
      }
}

无论如何..你真的确定真正需要强大的父/子关系吗?我认为你可以避免它并使一切更清晰,但你应该提供你的真实世界的例子(或更接近你真实世界的用法)以便提供帮助。

相关问题