创建一个类映射一个人是一个伟大的路要走!
首先,你可以创建一个人。cs文件在你的项目中是这样的:
public class Person() {
public string firstName {get; set;}
public string lastName {get; set;}
public string birthday {get; set;}
public Person(fName, lName, bDay) {
firstName = fName;
lastName = lName;
birthday = bDay;
}
// Addition by @MongZhu
public override ToString() {
return firstName + " " + lastName + " Birthday: " + birthday;
}
}
接下来,在你的表单代码中,你需要创建一个像这样的全局列表。把这个在你的代码的开始,或在您onLoad
事件:
List<Person> myList = new List<Person>;
确保您已使用System.Collections.Generic
顶部进口!
最后,当您点击您的'注册'按钮时,您想要将添加到列表中。 这可以在onClick
事件中完成的按钮:
myList.Add(new Person(tbfName.text, tblName.text, tbBirth.text);
现在你将有保存人的名单。但你也想打印! 在您要打印的清单,你已经添加你可以为了通过列表进行迭代并获得所需的信息做一个foreach
循环的新纪录也许以后无论触发:
foreach(Person p in myList) {
p.firstName // gets first name
p.lastName // gets last name
p.birthday // gets birthday
p.ToString() // Print all Person details -- Thanks @MongZhu
}
编辑 我已经修正了Person类中访问器的语法,如@MongZhu指出的那样,并且还展示了如何覆盖类中的ToString()
方法以快速打印出所有人的详细信息。
在你的意见,你要求更多了澄清如何将此分配至标签:
的foreach
代码可以去你的按钮的onClick()
事件。 点击“注册”后,新人将被创建并添加到列表中。在此代码后,您应该插入您的foreach:
// onClick
void btnRegister_Click(object sender, EventArgs e) {
myList.Add(new Person(tbfName.text, tblName.text, tbBirth.text); // Added person to list
// Create a string will all the person details
string full;
foreach(Person p in myList) {
full += p.ToString() + " "; // Print all Person details -- Thanks @MongZhu
}
// Update the label
lbDisplay.Text = full;
}
个人而言,我会购买一本关于C#编程的书。我希望这样一本书能教给我关于藏品之类的东西。 –
请张贴代码,你试过用'List' –
发布时,必须添加你有什么,如果你可以尝试,它有助于使一个圆形的问题是比较容易理解。此外,这将有助于提高你的技能,因为其他人经常会给你提示 – Harvey