我创建了一个名为 Student 的类,Program.cs 中有以下代码:
public static IList<Student> Students { get; private set; }
private static void AddStudent()
{
/*try
{
Console.Write("First name: ");
//Students.FirstName = Console.ReadLine();
string firstName = Console.ReadLine();
}
catch (ArgumentNullException)
{
Console.WriteLine("Name was left empty.");
}*/
Console.Write("First name: ");
string firstName = Console.ReadLine();
Console.Write("Last name: ");
string lastName = Console.ReadLine();
var newStudent = new Student {FirstName = firstName, LastName = lastName}; //if I use try-catch block, it says: The name 'firstName' doesn't exist in the current context
Students.Add(newStudent);
Console.WriteLine("The new student is added. \nEnter any key to return to main screen.");
Console.ReadKey();
}
public static void SortStudents(IList<Student> students)
{
string temp;
for (int i = 0; i < students.Count; i++)
{
for (int j = 0; j < students.Count; j++)
{
if (string.Compare(students[i].ToString(), students[j].ToString()) < 0)
{
//swap
temp = students[i].ToString();
students[i] = students[j];
students[j] = temp; //error here
}
}
}
Console.WriteLine(students);
}
学生班:
public class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string StudentNumber { get; set; }
public string Gender { get; set; }
public string FieldOfStudy { get; set; }
}
我正在尝试实现一种算法,该算法将按字母顺序对输入的名称进行排序,但它会在那里抛出错误。我该如何解决?我也在尝试使用 try-catch 块,但它抛出了我在代码中评论过的错误。提前致谢!
忽然笑
收到一只叮咚
相关分类