如何将子类的多个对象合并到单个父对象

时间:2017-08-22 13:08:51

标签: c#

我在单个父类中创建了四个类。由于所有子类都具有我们需要分配给不同值的各个属性 我们需要将子类的所有对象合并到父类,以便在创建时帮助我,并在方法参数中传递单个对象。

enter image description here

1 个答案:

答案 0 :(得分:1)

您现在拥有的不是类,而是嵌套类。你也不想要。你可能想要这个:

public class Person
{
  public string Name { get; set; }
  public int Age { get; set; }
}

public class A
{
  public Person B { get; set; }
  public Person C { get; set; }
  public Person D { get; set; }
  public Person E { get; set; }
}

internal static class Program
{
  private static void Method(A a)
  {
    Console.WriteLine(a.E.Name);
  }

  internal static void Main()
  {
    var a = new A 
             {
                B = new Person { Name = "Peter", Age = 31 }, 
                C = new Person { Name = "Paul", Age = 78 }, 
                D = new Person { Name = "Mary", Age = 24 }, 
                E = new Person { Name = "Jane", Age = 15 } 
             };

    Method(a);
  }
}