简体   繁体   English

C#试图从一个类的问题列表进入我的Main()类循环

[英]C# Trying to get a list of questions from one class into my Main() class loop

I'm trying to call questions that I made up from one class and then implement them into my Main() method. 我试图调用由一个类组成的问题,然后将其实现到Main()方法中。 The part that I am having trouble with is having the list read and looped through in my Main() method. 我遇到麻烦的部分是在Main()方法中读取并循环了列表。

So far, it reads like this: 到目前为止,它看起来像这样:

static void Main(string[] args)
{
    List<string> askQuestions = Questions();

    for (int i = 0; i < 2; i++)
    {
        Console.WriteLine(askQuestions[i]);

    }
}

static void Questions()
{
    List<string> question = new List<string>();

    question.add("q1");

    question.add("q2");

    //etc

}

I know I can get it to work if I just include the list in the Main() class, but the actual program will have hundreds of questions and I am trying to make it look a bit more readable. 我知道,只要将列表包含在Main()类中,我就可以使它工作,但是实际程序将有数百个问题,并且我试图使其看起来更具可读性。

First of all, you assign to a variable result of method, which doesn't have return type! 首先,您将分配给方法的变量结果,该方法没有返回类型! So it won't return anything, thus you cannot assign result of that method to variable. 因此它不会返回任何内容,因此您无法将该方法的结果分配给变量。

But your intention is clearly to return List in that method, so you should write your method like this: 但是您的意图显然是要在该方法中返回List ,因此您应该这样编写方法:

static List<string> Questions()
{
    List<string> question = new List<string>();
    question.add("q1");
    question.add("q2");
    //etc
    return question;
}

Why don't you just return the list: 您为什么不只返回列表:

    static void Main(string[] args)
    {
        List<string> askQuestions = Questions();

        for (int i = 0; i < 2; i++)
        {
            Console.WriteLine(askQuestions[i]);

        }
    }

    static List<string> Questions()
    {
        List<string> question = new List<string>();

        question.Add("q1");

        question.Add("q2");

        //etc

        return question;

    }

I will do a Question Class as suggested in other answers if there are more properties than just the questions, if you dont need it, then something similar to this can help you: 如果除了属性之外还有更多的属性,我将按照其他答案中的建议做一个问题类,如果您不需要它,那么类似的东西可以帮助您:

static void Main(string[] args)
{
    List<string> questions = Questions();

    questions?.ForEach(Console.WriteLine);
}

private static List<string> Questions()
{
    List<string> questions = new List<string> {"q1", "q2", "q3"};

    return questions;
}

Your "Questions" method's return type is void, Change the return type to list of type string and add a return statement. 您的“问题”方法的返回类型为空,将返回类型更改为字符串类型列表并添加一个返回语句。

static List<string> Questions()
{
  List<string> question = new List<string>();

  question.add("q1");

  question.add("q2");

  //etc
  return question;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM