将函数传递给main方法参数

时间:2015-06-06 21:39:24

标签: c# function args

我刚开始学习c#并需要一些帮助 我有一个任务,我需要声明2个函数加/减,需要传递给main方法[args],想法是在cmd我可以按1或2来传递一个特定的方法。
然后我需要将值返回给新函数。

这是我到目前为止所做的

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace addSubtractProject
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length >0)
            {
                if (args[0] =="1")
                    Console.WriteLine("You are using the Add Function" + );
            }
            else if (args[0] =="2")
                    Console.WriteLine("You are using the Minus Function");
         }
        int x =10, y =5;
        int z = addTwoNumbers(x, y);
        int i= minusTwoNumber(x,y);                                              

       //function Add Two Numbers
        static int addTwoNumbers (int a, int b)
            return (a + b);

          //function Minus Two Numbers
        static int minusTwoNumber (int a, int b)
            return (a - b);

}





    }

1 个答案:

答案 0 :(得分:0)

    class DelegatesTest
    {
        delegate int ComputeFunctionCallback( int x, int y );

        public static void Run()
        {
            string input = "";
            Console.Write( "Press 1 or 2:" ); input = Console.ReadLine();

            if ( input != "" )
            {
                ComputeFunctionCallback compute = null;

                switch ( input )
                {
                    case "1":
                        Console.WriteLine( "You are using the Add Function" );
                        compute = Add;
                        break;

                    case "2":
                        Console.WriteLine( "You are using the Subtract Function" );
                        compute = Subtract;
                        break;
                }

                Console.WriteLine( "Result is {0}", compute( 5, 2 ) );
            }
        }


        static int Add( int a, int b )
        {
            return ( a + b );
        }

        static int Subtract( int a, int b )
        {
            return ( a - b );
        }
    }