我已经看过并寻找答案,但我找不到答案。 是的,这是我的一类,但我的老师也不知道答案。他总是问我们是否先检查了谷歌。他正在和我们一起工作。所以,请帮助我们弄清楚什么是错的。 我不断得到错误:
Field' Program.birthday'永远不会被赋予,并且将永远具有其Mod3_Self .....默认值为null。
同样适用于Program.Validate
。
错误代码:CS0649
using System;
namespace Mod3_Self_Assessment
{
class Program
{
public static dynamic firstName;
public static dynamic lastName;
private static dynamic birthday;
public static dynamic tfName;
public static dynamic tlName;
public static dynamic course;
public static dynamic program;
public static dynamic degree;
private static dynamic validate;
public static dynamic validatebday;
static void Main(string[] args)
{
GetUserInformation();
PrintStudentDetails(firstName, lastName, birthday);
GetSchoolInformation();
PrintSchoolInformation(tfName, tlName, course, program, degree);
}
static void GetUserInformation()
{
Console.WriteLine("Enter the student's first name: ");
firstName = Console.ReadLine();
Console.WriteLine("Enter the student's last name");
lastName = Console.ReadLine();
//Code to finish getting the rest of the student data
Console.WriteLine("Enter your bithdate");
DateTime birthday = validate(Console.ReadLine());
}
private static DateTime Validatebday(string date)
{
try
{
DateTime birthday = DateTime.Parse(date);
if (birthday.AddYears(18).CompareTo(DateTime.Today) >0)
{
Console.WriteLine("The student is younger than 18 years of age.");
}
return birthday;
}
catch (FormatException)
{
Console.WriteLine("Invalid date format.");
return DateTime.Today;
}
}
static void PrintStudentDetails(string firstName, string lastName, string birthday)
{
Console.WriteLine("{0} {1} was born on: {2}", firstName, lastName, birthday);
Console.ReadLine();
}
static void GetSchoolInformation()
{
Console.WriteLine("Enter the teachers first name: ");
tfName = Console.ReadLine();
Console.WriteLine("Enter the teachers last name: ");
tlName = Console.ReadLine();
Console.WriteLine("Enter the course name: ");
course = Console.ReadLine();
Console.WriteLine("Enter the program name: ");
program = Console.ReadLine();
Console.WriteLine("Enter the degree name: ");
degree = Console.ReadLine();
}
static void PrintSchoolInformation(string tfName, string tlName, string course, string program, DateTime degree)
{
Console.WriteLine(
"Teacher: {1}, {0} " +
"\n Course: {2} " +
"\n Program: {3} " +
"\n Degree: {4}"
, tlName, tfName, course, program, degree);
}
}
}
答案 0 :(得分:2)
此代码中有两个“生日”变量。第一个被声明为类的公共静态动态属性。在方法GetUserInformation中,您声明一个名为“birthday”的局部变量,并且您正在分配“validate(Console.ReadLine());”到这个局部变量。您永远不会为类的属性赋值。 在“GetUserInformation”中删除第二个生日变量的声明。 它应该看起来像:
Console.WriteLine("Enter your bithdate");
birthday = validate(Console.ReadLine());
很确定这会解决问题。