初始化对象后对方法的nullreference

时间:2017-05-06 15:22:11

标签: c#

我在C#中相对较新,我只想使用该语言。

我有三个班,即学生,课程和年级。我似乎无法理解为什么它一直得到一个空值。

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类的对象设置了值。我也宣称它是吸气剂/二传手。我是在做代码还是缺少代码?

1 个答案:

答案 0 :(得分:3)

更正G班级中的Course二传手:

public Grade G
{
    get { return grade; }
    set { grade = value; }
}

并在使用Fabio建议之前设置G值:

s.C.G = new Grade(90.0, 90.0, 90.0);