如何以其他形式访问我的列表?

时间:2014-12-03 13:37:03

标签: c# list

我有一个员工和一个学生班,学生班如下所示。

public  class Student : Staff
{
    private int matriculationnumber;
    private  List<Student> studentlist = new List<Student>();
    public int Matriculationnumber
    {
        get
        {
            return matriculationnumber;
        }
        set
        {
            if (value < 1000 || value > 9000)
            {
                //ADD VALIDATION 
            }

            else
            {
                matriculationnumber = value;
            }


        }
    }

    public List<Student> StudentList 
    {
        get { return studentlist; }
        set { studentlist = value; }
    }
}

我还有一个GUI,允许用户输入学生或教职员的详细信息,然后点击下面显示的添加按钮将其添加到列表中

private void btnAdd_Click(object sender, RoutedEventArgs e)
{

    Student NewStudent = new Student();
    NewStudent.Name = txtName.Text;
    NewStudent.Address = txtAddress.Text;
    NewStudent.Email = txtEmail.Text;
    NewStudent.Matriculationnumber = Convert.ToInt32(txtPayMatNum.Text);
    List<Student> StudentList1 = NewStudent.StudentList;
    StudentList1.Add(NewStudent);

} 

我想知道如何以不同的形式访问此列表中的数据?

public partial class StudentMenu : Window
{
    public StudentMenu()
    {
        InitializeComponent();

        //Want to be able to access the list information here?!
    }
}

非常感谢任何帮助

2 个答案:

答案 0 :(得分:1)

您可以通过这种方式定义一个没有List

的类
public  class Student : Staff
{
    private int matriculationnumber;

    public int Matriculationnumber
    {
        get
        {
            return matriculationnumber;
        }
        set
        {
            if (value < 1000 || value > 9000)
            {
                //ADD VALIDATION 
            }

            else
            {
                matriculationnumber = value;
            }


        }
    }

}

可以使用List容器

创建公共静态类
public class StaticContext
{
      public static List<Student> studendList = new List<Student>();
}

创建Studend时,可以在内存中添加静态列表:

private void btnAdd_Click(object sender, RoutedEventArgs e)
{
   Student NewStudent = new Student();
   NewStudent.Name = txtName.Text;
   NewStudent.Address = txtAddress.Text;
   NewStudent.Email = txtEmail.Text;
   NewStudent.Matriculationnumber = Convert.ToInt32(txtPayMatNum.Text);

   StaticContext.studendList.add(NewStudent);
}

通过这种方式,您可以访问每个应用点的学生列表

public partial class StudentMenu : Window
{
    public StudentMenu()
    {
        InitializeComponent();

        //Want to be able to access the list information here?!
        //Use here 
        foreach (Student s in StaticContext.studendList)
        {
            //TODO
        }
    }
}

答案 1 :(得分:0)

我建议将studentlist移动到其他地方,以便可以从不同的形式访问它,这也有助于解耦模型和视图;即问题可以通过引入应用程序状态对象或类似的东西来解决。