class Family
{
public int FamilyId { get; set; }
public string Nickname { get; set; }
public Adults father { get; set; }
public Adults mother { get; set; }
public List<Person> Children { get; set; }
}
class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
class Adults : Person
{
public string Job { get; set; }
public int LicNumber { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Family> Families = new List<Family>();
Adults father = new Adults { Name = "Jim", Age = 34, Job = "Programmer", LicNumber = 2344454 };
Adults mother = new Adults { Name = "Amy", Age = 33, Job = "Nurse", LicNumber = 88888 };
Family fam1 = new Family { Nickname = "Family One", FamilyId = 1, father = father, mother = mother , };
Person child1 = new Person { Name = "Bob", Age = 4 };
Families.Add(fam1);
PrintFamily(fam1);
}
private static void PrintFamily(Family family)
{
Console.WriteLine($"{family.Nickname} ({family.FamilyId})");
Console.WriteLine("Prents : ");
Console.WriteLine($"{family.father.Name} - {family.father.Job} - {family.father.LicNumber}");
Console.WriteLine($"{family.mother.Name} - {family.mother.Job} {family.mother.LicNumber}");
Console.WriteLine("Kids");
Console.WriteLine($"( I WANT TO PRINT KIDS NAME AND AGE HERE, but it's not LETTING ME);
//I want to print Kids information as well. Like I did it with parents.
Console.ReadKey();
}
}
我的问题是:如何将Child1添加到集合中? // Family类中的儿童集合?我在这里做错了什么?我基于Person类创建了一个对象,并输入了姓名和年龄信息,但这并不能让我打印孩子的信息。
答案 0 :(得分:0)
在“ printFamily”方法中,您永远不会访问child1对象的成员属性。我建议为类型为Person的对象添加第二个参数,然后使用另一行代码访问Person对象的成员属性。
答案 1 :(得分:0)
您可以执行以下操作: 首张儿童名单:
class Family
{
public int FamilyId { get; set; }
public string Nickname { get; set; }
public Adults father { get; set; }
public Adults mother { get; set; }
public List<Person> Children = new List<Person>();
}
接下来添加子级:
static void Main(string[] args)
{
List<Family> Families = new List<Family>();
Adults father = new Adults { Name = "Jim", Age = 34, Job = "Programmer", LicNumber = 2344454 };
Adults mother = new Adults { Name = "Amy", Age = 33, Job = "Nurse", LicNumber = 88888 };
Family fam1 = new Family { Nickname = "Family One", FamilyId = 1, father = father, mother = mother , };
Person child1 = new Person { Name = "Bob", Age = 4 };
fam1.Children.add(child1); //Here add child to collection
Families.Add(fam1);
PrintFamily(fam1);
}
下一个打印的子级列表:
private static void PrintFamily(Family family)
{
Console.WriteLine($"{family.Nickname} ({family.FamilyId})");
Console.WriteLine("Prents : ");
Console.WriteLine($"{family.father.Name} - {family.father.Job} - {family.father.LicNumber}");
Console.WriteLine($"{family.mother.Name} - {family.mother.Job} {family.mother.LicNumber}");
Console.WriteLine("Kids:");
//read list and pirnt
foreach(Person per in family.Children){
Console.WriteLine($"{per.Name} ({per.Age})");
}
Console.ReadKey();
}
希望此帮助。