我试图遍历对象数组并从其他类中打印其属性。
我的主要课程是
class Program
{
static void Main()
{
//This to be change to relative path
string Path = @"C:\Users\";
string[] lines = { }; ;
//Reading file
if (File.Exists(Path))
{
lines = File.ReadAllLines(Path);
StudentReport.ReadStudents(lines);
}
else
{
Console.WriteLine("The file does't exist");
}
//Printing Students
PrintStudent.Print(lines.Length);
}
}
我正在使用此代码声明数组
public class StudentReport
{
public static void ReadStudents(string[] Lines)
{
//declare an array with the number of students
Student[] studentArray = new Student[Lines.Length];
int StudentCounter = 0;
foreach (string Line in Lines)
{
String[] Student = Line.Split(',');
//Calculating values
string ID = Student[0].PadLeft(10, '0');
string name = Student[1];
//Initialize the object
studentArray[StudentCounter] = new Student
{
FullName = name,
ID = ID,
};
StudentCounter++;
}
}
}
我正在使用此类来构造我的学生对象
class Student
{
public string FullName { get; set; }
public string ID { get; set; }
}
要输出学生对象的属性,我做了另一个课。问题是我无法从新类中访问对象数组的值。
我为输出而创建的类如下,但是我无法获取这些值。错误是“学生不包含学生数组的定义
public class PrintStudent
{
public static void Print(int StudentCounter)
{
for(int i = 0; i > StudentCounter; i++)
{
Console.WriteLine(Student.studentArray[i].FullName);
}
}
}
答案 0 :(得分:2)
您的错误是Student does not contain a definition for studentArray
。这是因为您的Student
类没有studentArray
,只有属性FullName
和ID
没有Student.studentArray[i]
。因此,访问PrintStudent.Print
没有任何意义。
可能您想要的是让ReadStudents返回studentArray,这样就不会超出范围,方法是更改方法签名以返回Student [],然后在最后调用return studentArray。
然后,您可以在参数中将studentArray传递给for(int i = 0; i > StudentCounter; i++)
方法。
顺便说一句,studentArray.Length
有一个错误<,并且永远不会运行(lines.Length为StudentCounter,它将始终为> = 0)
您可以使用--api-server-authorized-ip-ranges
或foreach循环遍历此数组,而不是传递StudentCounter。