You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#技术咨询:静态方法适用场景及待办清单项目方法调用问题

Hey there! Let's break this down step by step since you're new to C#—no worries, we've all fumbled with static vs instance methods when starting out.


First: Fixing the Method Calling Issue

Looking at your code snippet, I can guess the problem: your Menu() method is static, but the methods that actually interact with the to-do list (like adding items or viewing the list) are probably instance methods (since they need to access the actions list you initialize in the constructor).

Here's how to wire it up correctly in your main program:

  1. Create an instance of your ToDo class in your Main method—this gives you access to the instance-specific actions list and the methods that modify it.
  2. Call the static Menu() method to get the user's choice, then use your ToDo instance to run the corresponding action.

Here's a complete example building on your code:

using System;
using System.Collections.Generic;

class ToDo
{
    private List<string> actions;

    public ToDo()
    {
        actions = new List<string>();
    }

    // Static menu method: it only displays options, no need for instance data
    public static int Menu()
    {
        Console.WriteLine("Welcome to your To Do List!\n");
        Console.WriteLine("1. View the current list");
        Console.WriteLine("2. Add to list");
        Console.WriteLine("3. Exit");
        Console.Write("\nEnter your choice: ");
        
        // Basic input validation to avoid crashes
        if (int.TryParse(Console.ReadLine(), out int choice))
        {
            return choice;
        }
        else
        {
            Console.WriteLine("Oops, that's not a number. Try again!");
            return Menu(); // Recurse to ask again
        }
    }

    // Instance method: needs access to the specific ToDo instance's actions list
    public void ViewList()
    {
        Console.WriteLine("\nYour To Do List:");
        if (actions.Count == 0)
        {
            Console.WriteLine("  (Empty—time to add something!)");
        }
        else
        {
            for (int i = 0; i < actions.Count; i++)
            {
                Console.WriteLine($"{i+1}. {actions[i]}");
            }
        }
        Console.WriteLine();
    }

    // Another instance method: modifies the instance's actions list
    public void AddItem()
    {
        Console.Write("\nEnter the task to add: ");
        string task = Console.ReadLine().Trim();
        
        if (!string.IsNullOrWhiteSpace(task))
        {
            actions.Add(task);
            Console.WriteLine("Task added successfully!\n");
        }
        else
        {
            Console.WriteLine("Can't add an empty task—try again!\n");
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Create an instance of ToDo to hold our task list
        ToDo myToDoList = new ToDo();
        bool isRunning = true;

        while (isRunning)
        {
            int userChoice = ToDo.Menu();
            
            switch (userChoice)
            {
                case 1:
                    myToDoList.ViewList();
                    break;
                case 2:
                    myToDoList.AddItem();
                    break;
                case 3:
                    isRunning = false;
                    Console.WriteLine("Goodbye—happy tasking!");
                    break;
                default:
                    Console.WriteLine("Invalid choice, pick 1, 2, or 3!\n");
                    break;
            }
        }
    }
}

When to Use Static Methods

Static methods are great when:

  • The method doesn't need access to instance-specific data: Your Menu() method is perfect for this—it just prints text, no need to touch the actions list or any other instance field.
  • You're building utility/tool functions: Think Math.Abs() or string.Join()—these are static because they perform a generic action that doesn't depend on a specific object's state.
  • You're creating factory methods: Methods that help create instances of your class (e.g., ToDo.CreatePreloadedList() that returns a ToDo instance with default tasks).
  • The method is stateless: Its output only depends on the input parameters, not on any stored data in an instance.

A key rule to remember: Static methods can't access non-static fields or methods (like your actions list) because they don't belong to a specific instance of the class. That's why your list-modifying methods need to be instance methods!

内容的提问来源于stack exchange,提问作者Adam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:42:14