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();
}
}
}
c# 委托
最新推荐文章于 2024-07-10 17:37:23 发布