C#将派生类添加到Base类的集合中

时间:2014-04-04 03:06:08

标签: c# collections

  public abstract class Person
   {
      protected string name;

       public Person(string firstName)
      {
         name = firstName;
      }
   {

public BusinessPerson : Person
{
public BusinessPerson(string newName) : base(newName)
      {
      }
}

public class Group : CollectionBase
   {
      public void Add(Person newPerson)
      {
         List.Add(newPerson);
      }
   }

int Main 
{
    Group VariousPeople = new Group();
    VariousPeople.Add(new BusinessPerson("Jack")); // says invalid arguments
}

=============================================== =================================

如果我是正确的,那么多态性不允许我将派生类型存储在容器中 基础类型?为什么这对我不起作用?

1 个答案:

答案 0 :(得分:0)

对我来说很好。你在问题中的代码缺少一些大括号和东西,但一旦修复,它编译并在我的编译器上正常工作。固定代码如下。

internal class Program
{
    private static void Main(string[] args)
    {
        Group VariousPeople = new Group();
        VariousPeople.Add(new BusinessPerson("Jack"));
    }
}

public abstract class Person
{
    protected string name;

    public Person(string firstName)
    {
        name = firstName;
    }
}

public class BusinessPerson : Person
{
    public BusinessPerson(string newName)
        : base(newName)
    {

    }
}

public class Group : CollectionBase
{
    public void Add(Person newPerson)
    {
        List.Add(newPerson);
    }
}