【问题标题】:C# - Help understanding when to use static for a method [duplicate]C# - 帮助理解何时将静态用于方法[重复]
【发布时间】: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 怎么知道这不起作用!

标签: c# class methods static


【解决方案1】:
public void AddToList()

缺少基于您的 main 方法实现的 static 关键字。 如果方法不应该是静态的,请先创建 ToDo 类的对象实例。此外,您需要在循环添加用户选择检查。否则逻辑/实现将不会受到影响。这看起来像以下(未经测试):

 public enum Choices
 {
    Default, // 0
    ViewCurrentList, // 1
    AddToList, // 2
    DeleteFromList, // 3
    ClearList, // 4
    Exit // 5
 }

static void Main(string[] args)
{
    int userInput = 0;
    var toDo = new ToDo();

    do
    {
        userInput = ToDo.Menu();
        //If input = 2, call the Add to List method
        if (userInput == (int)Choices.AddToList)
        {
            toDo.AddToList();
        }


    } while (userInput != (int)Choices.Exit);   
 }

进一步:与其比较和使用整数,我建议在所有地方使用枚举来删除和避免“幻数”

【讨论】:

  • 您的回答并不能解决整个问题。再看一遍OP贴出来的代码..
  • 我不会在那里创建toDo。因为那么 OP 的下一个问题将是为什么当他在循环中执行此代码时,ToDo 中的所有操作总是为空的。而是使用ToDo 的相同实例并将其存储在循环之前声明的变量中。
  • @maccettura 你是对的。那不是问题的答案。看到没有人问过的事情'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多