从 C# 中的其他类读取对象值

问题描述 投票:0回答:1

我一直用 C++ 编写代码,但现在正在学习 C#。我在访问对象值时遇到了麻烦。

这是我尝试过的。

class Program
{         
    static void Main(string[] args)
    {
        StudentInfo[] student = new StudentInfo[2];

        student[0] = new StudentInfo(100, 4);
        student[1] = new StudentInfo(101, 3);

        Trying ty = new Trying();
        ty.trial(); /// I got trouble with this line
    }
}
class Trying
{
    StudentInfo[] student = new StudentInfo[2]; // I added this line since it prevents compiler error
    public void trial()
    {   
        Console.WriteLine(student[1].Gpa); // I got trouble with this line
    }
}
class StudentInfo
{        
    public int studentNo {get; set;}
    public int Gpa {get; set;}
    public StudentInfo(int cc, int ct)
    {
        studentNo = cc;
        Gpa = ct;
    }
}

错误显示:“未处理的异常。System.NullReferenceException:未将对象引用设置为对象的实例。”

如何在 Trying 类中正确访问值“student[1].Gpa”?

c# class object
1个回答
0
投票

您确实初始化了一个数组,但没有添加任何对象

class Trying
{
    StudentInfo[] students = new StudentInfo[2]; // <-- init array of nulls 

    // option 1
    students[0] = new StudentInfo(1, 1); 
    students[1] = new StudentInfo(2, 2);
    students[2] = new StudentInfo(3, 3);

    // option 2
    students = new StudentInfo[] 
    {
        new StudentInfo(1, 1),
        new StudentInfo(2, 2),
        new StudentInfo(3, 3)
    };
  
    public void trial()
    {   
        Console.WriteLine(student[1].Gpa); // I got trouble with this line
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.