将函数传递给 Main 方法 Args Cmd 提示符

Pass Function To Main Method Args Cmd Prompt

我正在尝试将加法或减法函数传递给主方法参数。在 cmd 中,如果我 运行 带有 1 的程序应该显示 AddFunction,如果我用 2 按下它应该显示 minusFunction。这是我到目前为止所做的,我有点卡住了

using System;

namespace addSubtractProject
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to Add and Subtract Program!");
            Console.WriteLine("============================");

            if (args.Length > 0)
            {
                if (args[0] == "1")
                {
                    Console.WriteLine("You are using the AddFunction");
                    (AddTwo);
                }
                else if (args[0] == "2")
                {
                    Console.WriteLine("You are using the subtractFunction");
                    (subtractTwo);

                    Console.ReadLine();
                }
                int x = 10, y = 5;
                int z = AddTwo(x, y); // function that returns a value
                int i = subtractTwo(x, y);

            }
        }

        //function Add Two Numbers
        static int AddTwo(int a, int b)
        {
            return (a + b);
        }

        //function Minus Two Numbers
        static int subtractTwo(int a, int b)
        {
            return (a - b);
        }
    }
}

稍作修改,您可以这样做:

    if (args.Length > 0)
    {
        int x = 10, y = 5;
        if (args[0] == "1")
        {
            Console.WriteLine("You are using the AddFunction");
            Console.WriteLine(string.Format("Result = {0}", AddTwo(x,y) ));
        }
        else if (args[0] == "2")
        {
            Console.WriteLine("You are using the subtractFunction");
            Console.WriteLine(string.Format("Result = {0}", subtractTwo(x,y) ));
        }
    }

希望这能给你一些想法。代码可以进一步改进,我会留给你自己尝试。