将函数传递给主方法参数和命令提示符
本文关键字:方法 参数 命令提示符 函数 | 更新日期: 2023-09-27 17:54:14
我试图传递一个添加或减去函数到主方法参数。在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) ));
}
}
希望这能给你一些想法。代码可以进一步改进,我将把它留给您自己尝试。