C#中关于对象和集合的使用,实现一对多的方法@TOC
实现对象和对象之间嵌套的关系,采用关键字List如图的嵌套关系
实现的代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Work
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
class Person
{
private string name;
private int age;
private string school;
public List<Family> f_list; //把集合类型作为一个成员变量
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public string School
{
get
{
return school;
}
set
{
school = value;
}
}
//Person类的构造器
public Person(string name,int age,string school)
{
this.name = name;
this.age = age;
this.school = school;
f_list = new List<Family>(); //在初始化的时候就创建一个集合,封装起来
}
}
class Family
{
private string f_name;
private string f_relation;
private int f_age;
private string f_work;
private string f_dept;
public string F_name
{
get
{
return f_name;
}
set
{
f_name = value;
}
}
public string F_relation
{
get
{
return f_relation;
}
set
{
f_relation = value;
}
}
public int F_age
{
get
{
return f_age;
}
set
{
f_age = value;
}
}
public string F_work
{
get
{
return f_work;
}
set
{
f_work = value;
}
}
public string F_dept
{
get
{
return f_dept;
}
set
{
f_dept = value;
}
}
//Family类的构造器
public Family(string f_name,string f_relation,string f_work,string f_dept,int f_age)
{
this.f_name = f_name;
this.f_relation = f_relation;
this.f_work = f_work;
this.f_dept = f_dept;
this.f_age = f_age;
}
}
class test
{
static void Main()
{
Person A = new Person("张三", 23, "中大");
Family a = new Family("张波", "爸爸", "腾讯", "研发", 46);
Family b = new Family("李娜" , "妈妈", "百度", "销售", 44);
A.f_list.Add(a); //把家庭成员添加到员工里面去
A.f_list.Add(b);
Console.ReadLine(); //编译通过
}
}
}