【发布时间】:2018-12-27 00:00:48
【问题描述】:
我正在尝试在 Student 类中创建属性 Age。我已经编写了下面的代码,但是当我运行它时,值 0 会立即分配给 age 变量。
我希望允许用户从控制台输入信息,但我还需要处理 Age 属性中可能出现的错误。
我在 Student 类中有以下代码:
private int age;
public int Age
{
get
{
return age;
}
set
{
string age1 = Console.ReadLine();
try
{
int.Parse(age1);
}
catch (ArgumentNullException)
{
Console.WriteLine("Age was not entered.");
}
catch (ArgumentOutOfRangeException)
{
if (value < 0 || value > 100)
{
Console.WriteLine("Please enter a valid age!");
}
/*else
{
age = value;
}*/
}
age = value;
}
}
public void PrintInformation()
{
Console.WriteLine($"Age: {Age} ");
}
这在 Main 方法中:
Console.Write("Please enter age: ");
Console.WriteLine(student.Age);
student.PrintInformation();
我需要这个输出-> 年龄:(从用户输入的年龄)。我该如何解决这个问题?
【问题讨论】:
-
你会想要从你的属性设置器中提取大部分逻辑。
-
在
set访问器中,起初您不使用隐式参数value来保存属性设置的值。相反,您考虑string age1 = Console.ReadLine();,并尝试将其解析为int(不获取结果值,并且不使用适用于此场景的TryParse方法)。最后,您毕竟将支持变量设置为value。你能看出问题吗? -
在尝试解决此问题时要问自己两个问题。 a) 为什么不对
int.Parse的返回值做任何事情? b)value来自哪里? -
这看起来像是大学项目分配的高潮。
标签: c# properties output