【发布时间】:2018-04-20 11:54:53
【问题描述】:
我遇到了一些代码问题,它覆盖了之前已声明的对象的名称。
我看不到修复。我尝试了很多次,但我的同学找不到解决方法,我的老师也找不到。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OOP
{
class Student
{
private static string name;
private static DateTime DOB;
private static int ID;
private static double height;
private static string tutor;
public Student()
{
Console.Clear();
//Console.WriteLine("This is for student: " + (count + 1));
Console.WriteLine("Please enter the student's name");
name = Console.ReadLine();
//tryagain:
//try
//{
// Console.WriteLine("Please enter the Date of Birth");
// DOB = DateTime.Parse(Console.ReadLine());
// DOB = DOB.Date;
//}
//catch
//{
// Console.WriteLine("Please enter a valid date format");
// goto tryagain;
//}
//Console.WriteLine("Please enter the Student's ID");
//ID = int.Parse(Console.ReadLine());
//Console.WriteLine("Please enter the Student's Tutor");
//tutor = Console.ReadLine().ToUpper();
//Console.WriteLine("Please enter the Student's height(cm)");
//height = double.Parse(Console.ReadLine());
}
public void DispayData()
{
Console.WriteLine("Name- " + name);
Console.WriteLine("Date of Birth- " + DOB.Date);
Console.WriteLine("ID- " + ID);
Console.WriteLine("Tutor- " + tutor);
Console.WriteLine("Height- " + height);
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter the number of students");
int numStuds = int.Parse(Console.ReadLine());
Student[] studs = new Student[numStuds];
for (int i = 0; i < numStuds; i++)
{
studs[i] = new Student();
}
Console.Clear();
for (int f = 0; f < numStuds; f++)
{
display(studs[f]);
}
Console.ReadKey();
}
static void display(Student stud)
{
stud.DispayData();
Console.WriteLine();
}
}
}
【问题讨论】:
-
这里有什么问题?你想解决什么问题?我看不到任何错误。
-
到底是什么问题?这段代码做什么?您期望它会做什么?当您在调试器中单步执行时,观察到的行为首先与预期的行为有何不同?那行确切的代码是做什么的?你期望它做什么?为什么?
-
不是一个修复方法,但老实说,我不会将
Console命令放入构造函数中。而是在您的循环中执行此操作并传入名称。 -
你的属性是静态的,请不要在构造函数中做所有这些工作,讨厌的东西!
-
此外,如果您想检查解析日期是否有效,请使用
DateTime.TryParse而不是捕获异常。并使用循环,而不是goto。