我是C#的新手,我正在尝试制作一个程序来提示用户输入关于8个vocalist.genre输入的信息,然后根据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个字段不是一个好主意;但是,您可以有一个字段,它是一个数组或列表:
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 Vocalist
{
public string Name {get;set;}
public string Origin {get;set;}
public string VocalistType {get;set;}
public string Genre {get;set;}
}
或者在最坏的情况下是只读结构
。