Map*_*pan 3 .net c# class list
我正在制作一个 SchoolApp 程序来学习 C# 并且我有这个主要功能,我正在尝试使其工作:
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
学校班级:
namespace SchoolApp
{
class School
{
public string name;
public School()
{
}
public School(string the_name)
{
name = the_name;
}
public void AddStudent(Student student)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
学生类:命名空间 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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我是 C# 的新手,对于我应该如何制作 AddStudent 以及如何使用 WriteLine 来编写类,我很困惑。输出应该是这样的:
学校:本地学校 James, 22 Jane, 23
有人建议使用 List<> 我遇到了同样的问题,对它的了解不够。
编辑:感谢大家的极快答复。我让它工作了,现在将开始深入阅读答案,这样我就不必再问相关问题了!
Console.WriteLine(t)
执行 t 到字符串的隐式转换。因此,您需要覆盖ToString()
所有类或显式从类创建字符串。
例子:
class School
{
public string name;
List<Student> Students = new List<Student>();
...
public override string ToString()
{
var stringValue = name;
foreach(var student in Students)
{
stringValue += student.ToString();
}
return stringValue;
}
}
class Student
{
public int Age;
public string Name;
...
public override string ToString()
{
return string.Format("{0} {1}", Name, Age);
}
}
Run Code Online (Sandbox Code Playgroud)