C#之委托学习一

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

namespace DelegateDemo1
{
    class Program
    {
        /// <summary>
        /// 定义一个返回string,没有参数的委托  delegate:委托关键字
        /// </summary>
        /// <returns></returns>
        delegate string GetAString();
        /// <summary>
        /// 定义一个没有返回值,带一个int类型参数的委托
        /// </summary>
        /// <param name="x"></param>
        delegate void IntMethodInvokder(int x);
        /// <summary>
        /// 定义一个返回double,带2个参数的委托  定义委托:等同于定义一个新类
        /// </summary>
        /// <param name="first"></param>
        /// <param name="second"></param>
        /// <returns></returns>
        delegate double TwoLongOp(long first, long second);


        delegate double DoubleOp(double x);


        static void ProcessAndDisplayNumber(DoubleOp action, double value)
        {
            //action:调用方法的函数地址,从内存读取  所以通过传递进来的方法名 就可以调用对应的函数
            double result = action(value);
            Console.WriteLine("values is " + value + "  result is " + result);
        }

        static void Main(string[] args)
        {
            int x = 40;
            //x.ToString:方法的地址   x.ToString():调用方法
            GetAString firstStringMethod = x.ToString;
            //简单应用委托
            Console.WriteLine("firstStringMethod " + firstStringMethod());
            //定义委托数组 数组的元素是方法名(方法的内存地址) 
            DoubleOp[] operations = { MathOperations.MultiplyByTwo, MathOperations.Squre };
            for (int i = 0; i < operations.Length; i++)
            {
                ProcessAndDisplayNumber(operations[i], 3.0);
            }
            Console.ReadKey();
        }
    }

    class MathOperations
    {
        public static double MultiplyByTwo(double value)
        {
            return value * 2;
        }

        public static double Squre(double value)
        {
            return value * value;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值