【发布时间】:2013-11-27 00:14:41
【问题描述】:
我正在尝试获取列表中的所有名称并将它们显示在列表框中。这是我的代码。
namespace UniRecords
public partial class MainWindow
{
private University uni = new University(); //Creates a new University object
public MainWindow()
{
InitializeComponent();
}
private void btnadd_Click(object sender, RoutedEventArgs e)
{
Student newStudent = new Student(txtname.Text, txtaddress.Text, txtmatric.Text,txtcourse.Text); //Calls the student constructor to construct a student object
uni.ownsStudent(newStudent); //Calls the newStudent method in the University class
}
private void btnshow_Click(object sender, RoutedEventArgs e)
{
uni.showStudents(); //calls the showStudents method
}
private void btnlist_Click(object sender, RoutedEventArgs e)
{
}
}
}
我的大学班级:
namespace UniRecords
class University
{
//Creates a list of students that University owns
private List<Student> owns = new List<Student>();
public University()
{
}
public void ownsStudent(Student newStudent)
{
owns.Add(newStudent);//Adds a new student to the list
}
public void showStudents()
{
foreach (Student s in owns)
{
System.Windows.MessageBox.Show(s.printDetails()); //Prints out details of each student individually
}
}
public void getStudents()
{
foreach (Student s in owns)
{
}
}
}
}
学生班级:
namespace UniRecords
class Student
{
private string name;
private string dob; //Date of birth
private string course;
private string matric;
private string address;
//Constructor
public Student(string myname, string myaddress, string mymatric, string mycourse)
{
Name = myname;
Address = myaddress;
Matric = mymatric;
Course = mycourse;
}
//Uses get and set to make sure that the variables are kept private
public string Name
{
get { return name; }
set { name = value; }
}
public string Dob
{
get { return dob; }
set { dob = value; }
}
public string Course
{
get { return course; }
set { course = value; }
}
public string Matric
{
get { return matric; }
set { matric = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public string printDetails()
{
return "student is called " + Name + " " + Address + " " + Matric + " " + Course;
}
public void listNames()
{
}
}
}
我正在尝试按下 btnlst_click 并输出所有已输入名称的列表。
我知道我需要使用类似的东西:foreach (Student s in owns),但我没有权限从主窗口类执行此操作,我不确定如何将它从大学类传递到主窗口放在字符串中。有人可以提供建议吗?
【问题讨论】:
-
您可以将
Student和University课程标记为公开吗? -
@Nogard:它们在同一个命名空间中,没关系。当前的可访问性就足够了。
标签: c# list permissions