Чтение значения объекта из другого класса в С#C#

Место общения программистов C#
Anonymous
Чтение значения объекта из другого класса в С#

Сообщение Anonymous »

Я всегда программировал на 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: ссылка на объект не установлена ​​на экземпляр объекта.

Как я могу получить доступ к значению Student[1].Gpa правильно в классе Trying?

Подробнее здесь: https://stackoverflow.com/questions/781 ... in-c-sharp

Вернуться в «C#»