当前位置: 首页 > 知识库问答 >
问题:

如何在for循环中使用struct元素?

宦高岑
2023-03-14

我是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();
    }
    
    
    
}

}

共有1个答案

闾丘德宇
2023-03-14

您不能通过名称组合访问字段,所以有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;}
}

或者在最坏的情况下是只读结构

 类似资料:
  • 问题内容: 因此,我正在为不和谐而开发一个聊天机器人,现在正在开发一个可以用作待办事项列表的功能。我有一个命令可以将任务添加到列表中,并将它们存储在字典中。但是,我的问题是以更易读的格式返回列表(参见图片)。 任务存储在一个称为中。但是,为了使bot实际发送消息,我需要使用一条语句,否则它将仅将其打印到控制台而不是实际的聊天记录(参见图片)。 这是我尝试解决的方法,但是由于我使用了for循环,因此

  • 问题内容: 我正在努力理解为什么我的代码处于一种状态而不是另一种状态。自从我讲完指针已经有一段时间了,所以我可能会生锈! 基本上,我有一个用于将对象存储在内存中的具有功能的存储库结构。 因此,它所做的全部工作就是将RW互斥锁锁定在其上,并将指针添加到由标识符引用的映射中。 然后,我得到了一个功能,该功能将基本上遍历这些对象的一部分,并将它们全部存储在存储库中。 上面的方法不起作用,看起来一开始一切

  • 问题内容: 我有一个清单 我想在如下所示的for循环中删除此列表中的元素: 但这是行不通的。我能做什么? 问题答案: 使用循环遍历列表时,不允许从列表中删除元素。 重写代码的最佳方法取决于你要执行的操作。 例如,你的代码等效于: 另外,你可以使用while循环: 我正在尝试删除符合条件的项目。然后我转到下一个项目。 你可以将每个不符合条件的元素复制到第二个列表中: 或者,你可以使用filter或列

  • 你能帮助我,如何在代码中添加“for”循环吗?目标是从所有注释中只显示3条注释,这些注释是用.map扫描的。 我试着把它放在这里,但我发现它在JSX中不起作用。 或者你会推荐用另一种方式来解决任务?

  • 我想使用useEffect和for-loop生成多个JSX元素,但在本例中没有呈现任何内容。 警告代码:“React Hook useEffect缺少依赖项:”Render InfoCard“。请包含它或删除依赖项数组React-Hooks/EXEXTIVE-DEPS”