函数的委托和重载

using System;
using System.Collections;
namespace vehicle
{
    public delegate double MyDelegate(double param1,double param2);//定义一个委托
    class Program
    {
        static double Mul(double param1,double param2)
            
        {
            return param1*param2;
        }
        
        static double Div(double param1,double param2)
        {
            return param1/param2;
        }
        public static void Main(string[] args)
        {
            MyDelegate de;
            de=Mul;//定义一个委托de,指向Mul函数
            Console.WriteLine(de(3.0,3.0));
            de=Div;
            Console.WriteLine(de(6.0,3.0));
            Console.ReadKey();
        }
    }
}

定义一个委托跟函数差不多,区别在于

1.定义委托需要加上delegate关键字

2.委托的定义不需要函数体

【定义变量只能指向一个数据,而定义一个委托,委托是可以指向函数的】

using System;
using System.Collections;
namespace vehicle
{
    class Program
    {
        static int MaxValue(params int[] array)//找寻整数数组中最大的一个数
        {
            Console.WriteLine("调用int");
            int maxValue=array[0];
            for(int i=1;i<array.Length;i++)
            {
                if(array[i]>maxValue)
                    maxValue=array[i];
            }
            return maxValue;
        }
        static double MaxValue(params double[] array)//找寻小数数组中最大的一个数
        {
            Console.WriteLine("调用double");
            double  maxValue=array[0];
            for(int i=1;i<array.Length;i++)
            {
                if(array[i]>maxValue)
                    maxValue=array[i];
            }
            return maxValue;
        }        
        
        public static void Main(string[] args)
        {
            int res=MaxValue(234,4,56);//根据用户输入的不同数值来重载不同的函数
            double res2=MaxValue(23.6,234.5,56.34);
            Console.WriteLine(res);
            Console.WriteLine(res2);
            Console.ReadKey();
        }
    }
}

重载函数就是函数名相同,但是函数的参数不同,在进行函数调用的时候,系统会根据用户输入的数据自动的调用相应的函数。

posted @ 2017-08-15 14:41  battly  阅读(248)  评论(0编辑  收藏  举报