C#中的结构数组
发布时间:2020-12-15 08:35:22 所属栏目:百科 来源:网络整理
导读:我正在尝试使用结构数组从用户那里获得输入然后打印它: using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace CA4{class Program{ static void Main(string[] args) { StudentDetails[,] student = new StudentDe
我正在尝试使用结构数组从用户那里获得输入然后打印它:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CA4 { class Program { static void Main(string[] args) { StudentDetails[,] student = new StudentDetails[5,1]; Console.WriteLine("Please enter the unit code:"); student[0,0].unitCode = Console.ReadLine(); Console.WriteLine("Please enter the unit number:"); student[1,0].unitNumber = Console.ReadLine(); Console.WriteLine("Please enter first name:"); student[2,0].firstName = Console.ReadLine(); Console.WriteLine("Please enter last name:"); student[3,0].lastName = Console.ReadLine(); Console.WriteLine("Please enter student mark:"); student[4,0].studentMark = int.Parse(Console.ReadLine()); for (int row = 0; row < 5; row++) { Console.WriteLine(); for (int column = 0; column < 1; column++) Console.WriteLine("{0} ",student[row,column]); } Console.ReadLine(); } public struct StudentDetails { public string unitCode; //eg CSC10208 public string unitNumber; //unique identifier public string firstName; //first name public string lastName;// last or family name public int studentMark; //student mark } } } 不幸的是,输入所有数据后我得到: CA4.Program+StudentDetails CA4.Program+StudentDetails CA4.Program+StudentDetails CA4.Program+StudentDetails CA4.Program+StudentDetails 它不会崩溃,只是代替我输入的数据获得上述5行. 我知道它不起作用的原因是我没有正确使用结构,因为没有它们没有问题. 有人可以帮助我,并告诉我如何在上面的例子中使用结构.谢谢 干杯, n1te 解决方法
您对Console.WriteLine(“{0}”,学生[行,列])的调用;隐式调用StudentDetails结构的ToString()方法,默认情况下只写出结构类型的名称.重写ToString()方法:
public struct StudentDetails { public string unitCode; //eg CSC10208 public string unitNumber; //unique identifier public string firstName; //first name public string lastName;// last or family name public int studentMark; //student mark public override string ToString() { return string.Format("{0},{1},{2},{3},{4}",unitCode,unitNumber,firstName,lastName,studentMark); } } 但是,更大的问题是你要设置5个不同的StudentDetails结构的属性……通过声明一个数组StudentDetails [,] student = new StudentDetails [5,1];并要求用户输入有关数组中不同点的结构的详细信息,即学生[0,0]然后学生[1,0],你没有制作一个StudentDetails对象并在其上设置属性,你创建了5个不同的StudentDetails对象. 你为什么要使用阵列?如果您希望用户填写单个StudentDetails对象,请执行此操作 StudentDetails student = new StudentDetails(); Console.WriteLine("Please enter the unit code:"); student.unitCode = Console.ReadLine(); Console.WriteLine("Please enter the unit number:"); student.unitNumber = Console.ReadLine(); ... 然后把它写出来: Console.WriteLine("{0}",student); 这将使用您在StudentDetails结构中声明的ToString()方法. (只要需要将对象转换为字符串,就会调用ToString(),您不必总是编写它) 希望这可以帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |