我一直用 C++ 编写代码,但现在尝试学习 C#。我试图创建多个对象并在 C# 中使用它们的数据。然而,它并没有按照我想要的方式工作。
这是我尝试过的代码。
class Students
{
static void Main(string[] args)
{
StudentInfo[] student = new StudentInfo[2];
student[0] = new StudentInfo(100, 4);
student[1] = new StudentInfo(101, 3);
for (int i = 0; i < 2; i++)
{
Console.WriteLine(student[i].studentNo);
Console.WriteLine(student[i].GPA);
}
}
class StudentInfo
{
public int studentNo, GPA;
public StudentInfo(int cc, int ct)
{
int studentNo = cc;
int GPA = ct;
}
}
}
我期望得到
100
4
101
3
但我实际看到的是
0
0
0
0
它给了我一个警告,“警告 CS0649:字段 'Students.StudentInfo.GPA' 永远不会分配给,并且将永远分配给。”
如何正确设置对象中的这些值?
class StudentInfo
{
public int studentNo, GPA;
public StudentInfo(int cc, int ct)
{
studentNo = cc;
GPA = ct;
}
}
尝试这段代码,你已经在studentifo类中进行了int处理。删除studentInfo函数中的int