【问题标题】:How to assign values to the elements of a string array in C#?如何在 C# 中为字符串数组的元素赋值?
【发布时间】:2018-12-09 23:59:09
【问题描述】:

我是 C# 的初学者,我有以下代码:

string[] student = new string[6] { "Joules", "Niki", "Hannah","Ariana", "Martin", "Loren" };
int[] mark = new int[6] { 85, 65, 70, 75, 95, 80 };
        Console.Write(student[0]);
        student[0] = mark[0].ToString();
        Console.WriteLine($"'s mark is {student[0]}");

我创建了一个学生字符串数组,我正在尝试为每个学生分配值(标记)。我发布的这段代码并不准确,我需要一些帮助来理解这个过程。 非常感谢。

【问题讨论】:

    标签: c# arrays string


    【解决方案1】:

    我会避免继续使用这种方法,因为它处理起来很麻烦。相反,创建一个类来表示具有必要字段的数据。

    例子:

    class Student {
       public string Name {get; set;}
       public int Mark {get; set; }
    }
    

    然后构造Student 对象并填充我将留给您作为练习的数据。

    请参阅文档以获取更多帮助 Objects (C# Programming Guide),因为它包含一些您可以使用的好示例。

    【讨论】:

    • 鼓励 OP 将其抽象出来并导致良好的编码模式的好答案。
    【解决方案2】:

    //以防万一,如果您只是想分别在名称上打印值标记...

        string[] student = new string[6] { "Joules", "Niki", "Hannah","Ariana", "Martin", "Loren" };
        int[] mark = new int[6] { 85, 65, 70, 75, 95, 80 };    
    
        //student.Length or mark.Lenght, whatever
        for(int i = 0; i < student.Length ; i++ ) 
        Console.WriteLine($"{student[i]}'s mark is {mark[i]}");
    

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 1970-01-01
      • 2012-05-24
      • 2011-12-08
      • 2017-09-27
      • 2016-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多