我正在尝试使用结构数组从用户那里获取输入,然后打印它:
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
最佳答案
这是因为默认情况下 ToString()
返回类型名称,您必须自己为 StudentDetails
覆盖它结构:
public struct StudentDetails
{
public override void ToString()
{
return String.Format(
CultureInfo.CurrentCulture,
"FirstName: {0}; LastName: {1} ... ",
this.FirstName,
this.LastName);
}
}
顺便说一句,你为什么要使用 stuct 和 legacy 数组?考虑使用 class
相反 struct
和通用 IList<StudentDetails>
或 IDictionary<int, StudentDetails>
而不是数组。
因为遗留数组和结构(基本上是值类型)在每次将项目添加到数组时引入装箱(结构 -> 对象)并在读回时取消装箱(对象 -> 结构)。
关于c# - C# 中的结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7050923/