c# 委托

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//委托是一种安全地封装方法的类型,它与 C 和 C++ 中的函数指针类似
namespace delegateExample
{
    delegate int Math(int x,int y);// 声明一个委托
    delegate void MathMulti(int x,int y);// 多路委托返回要为void 
    class ADD_SUB
    {
        public int Add(int x, int y)
        {
            return x + y;
        }
        public int Sub(int x, int y)
        {
            return x - y;
        }
    }
    class MUL_DIV
    {
        static public void Mul(int x, int y)// 可以委托静态与非静态的方法
        {
            Console.WriteLine("x*y is {0}",x*y);
        }
        static public void Div(int x, int y)
        {
            Console.WriteLine("x/y is {0}", x / y);
        }
    }
    class DeleParam//委托类型派生自 .NET Framework 中的 Delegate 类 当然可以做参数 
    {
        public static void MethodWithCallback(int param1, int param2, MathMulti callback)
        {
            callback(param1 , param2);
        }
    }
    //协变和逆变会提供用于使委托类型与方法签名匹配的灵活性
    class Animal { }
    class Fish : Animal { };

    class Program
    {
        public delegate Animal AnimalMethod();//关于协变 协变允许方法具有的派生返回类型比委托中定义的更多
        public static Fish FishMethod() 
        {
            Console.WriteLine("FishMethod");
            return null;
        }

        private void MultiHandler(object sender, System.EventArgs e)//逆变 将委托与具有某个类型的参数的方法一起使用,这些参数是委托签名参数类型的基类型
        {
            Console.WriteLine(e.ToString());
        }

        static void Main(string[] args)
        {
            ADD_SUB addsub = new ADD_SUB();
            
            Math math1 = new Math(addsub.Add);
            Console.WriteLine("{0}",math1(1,2));//3
            
            MathMulti math2 = new MathMulti(MUL_DIV.Mul);
            math2(1, 3);//is 3

            math2+= new MathMulti(MUL_DIV.Div);// math2 现在有两种方法被调用
            math2(1,4);// is 4        is 0

            math2-= new MathMulti(MUL_DIV.Div);// math2 现在只有乘法方法被调用
            math2(1, 5);// is 5 

            DeleParam.MethodWithCallback(6, 1, MUL_DIV.Mul);// is 6 

            AnimalMethod am = FishMethod;
            am();

            

            Console.ReadLine();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值