我在C#中相對較新,我只是想在語言中使用它。初始化對象後的方法nullreference
我有三個班,即學生,課程和成績。我似乎無法理解爲什麼它始終得到一個空值。
class Student
{
Name name;
Course course;
public Student(Course course)
{
this.course = course;
}
public Course C
{
get { return course; }
set { course = value; }
}
}
class Course
{
string name;
string code;
int units;
Grade grade; // this one warns as 'Course.grade' is never assigned to, and will always have its default value null
public Course(string name, string code)
{
this.name = name;
this.code = code;
}
public void DisplayDetails()
{
Console.WriteLine("Course: {0}({1})", code, name);
}
public int U
{
get { return units; }
set { units = value; }
}
public Grade G
{
get { return grade; }
set { value = grade; }
}
}
class Grade
{
double q;
double o;
double fe;
double fg;
public Grade(double q, double o, double fe)
{
this.q = q;
this.o = o;
this.fe = fe;
}
public void ComputeGrade()
{
fg = q * .5 + o * .2 + fe * .3;
}
public double C
{
get { return fg; }
set { value = fg; }
}
}
這是我的主要課程。
class Program
{
static void Main(string[] args)
{
Student s = new Student(new Course("Something", "1234"));
s.C.U = 3;
s.N = new Name("John", "Snow");
Grade grade = new Grade(90.0, 90.0, 90.0); // I have initialized an object here
s.C.G.ComputeGrade(); //but this gets a null value
s.N.Display2();
s.C.DisplayDetails();
Console.WriteLine(" - {0} units", s.C.U);
Console.WriteLine(" Grade: {0}", s.C.G.C); //as well as this
Console.ReadKey();
}
}
我相信已經設置了Grade對象的值。我也宣佈它是getter/setter。我是在做錯代碼還是缺少代碼?
配套G使用前:'SCG =新級(90.0,90.0,90.0 );',那麼你可以使用它'sCGComputeGrade();' – Fabio
@Fabio CodeFuller的回答正確地指出,這沒有任何影響,因爲'G'的屬性設定器實際上什麼都不做。 – hvd
其實法比奧也是對的,有正確的二傳手是一半的工作。但是setter從來不會在代碼中調用。 – CodeFuller