带类的WriteLine [英] WriteLine with a class
问题描述
我正在编写SchoolApp程序以了解C#,并且我要尝试执行以下主要功能:
I'm making a SchoolApp program to learn about C# and I have this main function that I'm trying to make work:
namespace SchoolApp
{
class Program
{
public static void Main(string[] args)
{
School sch = new School("Local School");
sch.AddStudent(new Student { Name = "James", Age = 22 }); // this function
sch.AddStudent(new Student { Name = "Jane", Age = 23 });
Console.WriteLine(sch); // this implementation
}
}
}
学校课程:
namespace SchoolApp
{
class School
{
public string name;
public School()
{
}
public School(string the_name)
{
name = the_name;
}
public void AddStudent(Student student)
{
}
}
}
学生班: 命名空间SchoolApp
Student class: namespace SchoolApp
{
class Student
{
public int Age;
public string Name;
public Student()
{
Age = 0;
Name = "NONAME";
}
public string _name
{
get
{
return this.Name;
}
set
{
Name = value;
}
}
public int _age
{
get
{
return this.Age;
}
set
{
Age = value;
}
}
}
}
我是C#的新手,我对应该如何制作AddStudent以及如何使用WriteLine编写类非常困惑.输出应遵循以下几行:
I'm new to C# and I am pretty lost as to how I should make the AddStudent and how to work with the WriteLine to write the class. The output should be along these lines:
学校:当地学校 詹姆斯22岁 简,23
School: Local School James, 22 Jane, 23
有人建议使用List<>我遇到了同样的问题,那就是对它的了解不足.
Someone suggested using List<> I hit the same problem of not knowing enough about it.
谢谢大家的快速答复.我已经开始使用它,现在将深入阅读答案,这样我就不必再问相关问题了!
Thank you all for your extremely fast answers. I got it working and will now commense reading the answers in depth so I don't have to ask related questions again!
推荐答案
在您的School
类中,您似乎想拥有一个私有的Student列表.列表很简单,在您的情况下,它采用通用类型Student
,您可以在其中添加项目或从中删除项目.
In your School
class it looks like you want to have a private list of Students. List is simple, it takes in a generic type, in your case Student
and you can add and remove items to/from it.
在您的School
类中使用:
private List<Student> students;
在您的AddStudent代码中,您可以简单地使用:
And in your AddStudent code you could simply use:
students.Add(student); // student is the variable being passed in and students is the list. NOTE: You will have to make sure students is intalized to a new List of Student. students = new List<Student>();
看看以下链接. MSDN是适当的文档,但是dotnetperls对于像这样的简单东西很有用.
Take a look at the following links. MSDN is the proper documentation, but the dotnetperls is good for simple stuff like this.
http://msdn.microsoft.com/en-gb/library/3wcytfd1.aspx
http://www.dotnetperls.com/list-add
这篇关于带类的WriteLine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!