【发布时间】:2018-08-30 16:34:20
【问题描述】:
我是 C# 新手,我为自己设置了一个迷你项目,用于创建一个待办事项列表类型的应用程序,其中有一个设置菜单,你可以从菜单等中选择一个选项。
我在调用主类中的方法时遇到问题。这是我的代码:
class ToDo
{
public ToDo()
{
actions = new List<string>();
}
public static int Menu()
{
Console.WriteLine("Welcome to your To Do List!\n");
Console.WriteLine();
Console.WriteLine("\n1. View the current list?");
Console.WriteLine("\n2. Add to list?");
Console.WriteLine("\n3. Delete from the list?");
Console.WriteLine("\n4. Clear the list?");
Console.WriteLine("\n5. Exit \n");
Console.Write("\nWhat Would you like to do?: ");
var selection = Console.ReadLine();
return Convert.ToInt32(selection);
}
public void AddToList()
{
Console.WriteLine("What would you like to add to the list?");
string userInput = Console.ReadLine();
actions.Add(userInput);
}
和我的主要方法:
class Program
{
static void Main(string[] args)
//Keep displaying menu till user chooses option 5. Exit
{
int userInput = 0;
do
{
userInput = ToDo.Menu();
} while (userInput != 5);
//If input = 2, call the Add to List method
if (userInput == 2)
{
ToDo.AddToList();
}
}
}
我遇到的问题是在 main 方法中,它没有调用“ToDo.AddToList();”。
有人可以帮忙吗?或者,如果我接近这个完全错误,任何建议将不胜感激!
谢谢
【问题讨论】:
-
在
Main中,创建ToDo的实例并将其存储在变量f.e.ToDo todo = new Todo();。现在你可以使用todo.AddToList(); -
逐步分析你的逻辑。当输入不等于 5 时,您的循环继续,您的
if语句在该循环之外,它会检查输入是否等于 2。那时它怎么可能等于 2? -
当它的逻辑不影响对象的状态时,你使用静态方法。 ClassName 直接调用的静态方法。而类的非静态成员只能通过类的实例访问
-
这如何编译?
AddToList不是静态的。这方面的主要问题是@maccettura 指出的。从未到达与AddToList相关的块。 -
是的,我知道,如果不编译,OP 怎么知道这不起作用!