c# - C# 中的结构数组

标签 c# arrays struct

我正在尝试使用结构数组从用户那里获取输入,然后打印它:

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/

相关文章:

c# - 在 wpf 数据网格中动态添加复选框列

c# - 为什么我的代码不能编译?

c - 仍然不明白 C 中指向数字数组的指针

javascript - 我的递归 javascript 函数做错了什么?

c++ - 未声明的结构名称和交换函数在没有通过引用传递的情况下进行交换

c# - DependencyProperty 对于多个 FrameworkElement 实例的行为

c# - 使用 OpenXML 将 Word docx 转换为 Excel

php - 如何在 PHP 中访问嵌套标准对象数组中的数据

go - 在 Go 中访问结构属性

C# - 取消绑定(bind)结构 "destruction"上的事件