【问题标题】:How do I use a struct element in a for loop?如何在 for 循环中使用结构元素?
【发布时间】:2021-03-14 14:23:42
【问题描述】:

我是 C# 新手,我正在尝试制作一个程序,提示用户输入有关 8 位歌手的信息,然后根据 vocalist.genre 输入的内容将这些信息分类到文本文件中。但是,当我尝试将 for 循环用于用户的输入时,我遇到了问题。我该怎么办?

using System;
using System.IO;

struct vocalists
{
    public string name;
    public string origin;
    public string vocalist_type;
    public string genre;
};

public class test
{

public static void Main(string[] args)
{
    vocalists vocalists1;
    vocalists vocalists2;
    vocalists vocalists3;
    vocalists vocalists4;
    vocalists vocalists5;
    vocalists vocalists6;
    vocalists vocalists7;
    vocalists vocalists8;
    
    //Vocalists inputs

    for (int i = 1; i < 9; i++)
    {
        Console.WriteLine("Enter the vocalists {0} name: ", i);
        //Here I'm supposed to do something in the format of vocalistsi.name=Console.ReadLine();
        Console.WriteLine("Enter the vocalists {0} origin: ", i);
        //Here I'm supposed to do something in the format of vocalistsi.origin=Console.ReadLine();
        Console.WriteLine("Enter the vocalists {0} type: ", i);
        //Here I'm supposed to do something in the format of vocalistsi.type=Console.ReadLine();
        Console.WriteLine("Enter the vocalists {0} genre: ", i);
        //Here I'm supposed to do something in the format of vocalistsi.genre=Console.ReadLine();
    }
    
    
    
}

}

【问题讨论】:

  • 你期待什么行为?
  • 使用数组代替 8 个变量
  • 像@juharr 我会建议使用数组或列表,而不是像你那样做。但如果您坚持使用变量名,您可以在 Google 上搜索“C# 中的反射”。

标签: c# loops for-loop structure


【解决方案1】:

您无法通过名称组合访问字段,因此拥有 8 个字段不是一个好主意;但是,您可以拥有一个数组或列表字段:

List<Vocalist> vocalists = new List<Vocalist>();
// now use vocalists.Add(...) and vocalists[i]

Vocalist[] vocalists = new Vocalist[8];
// now use vocalists[i]

我还应该指出,将Vocalist 用作struct 是一个糟糕的想法,会伤害你。应该是class:

class Vocalist
{
    public string Name {get;set;}
    public string Origin {get;set;}
    public string VocalistType {get;set;}
    public string Genre {get;set;}
}

或者最坏的情况readonly struct

【讨论】:

  • 我知道...我也不想使用 struct,但由于这是针对项目的,因此说明明确指出必须为歌手制作一个 struct。
  • @FedonKotsakis 这是学生的事吗?老实说,写这些说明的人……好吧,我会说“很可能有一些误解”;如果它学生的事情,如果他们想知道为什么这是错误的,请随时指出我的导师。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-22
  • 2021-01-22
相关资源
最近更新 更多