帮助理解委托、匿名委托、Lambda表达式还有事件

写了一个小程序,能够很好的认识到这三个的用法

namespace Lambda
{
/// <summary>
/// 实现根据指定运算形式 输出结果
/// </summary>
class Program
{
delegate int TwoInt32OperationDel(int paramA, int paramB);
static void Operation(TwoInt32OperationDel del)
{
for (int i = ; i < ; i++)
{
for (int y = ; y < ; y++)
{
int result = del(i, y);
Console.Write("{0}and{1}={2} ",i,y,result);
}
Console.WriteLine();
}
}
private static int twoInt32Plus(int a, int b)
{
return a + b;
}
private static int twoInt32Multi(int a, int b)
{
return a * b;
}
static void Main(string[] args)
{
////1 匿名委托方法调用:(匿名方法只是简化了一下代理的写法)
// Console.WriteLine("A+B");
// Operation(delegate(int a, int b) {return a + b; });
// Console.WriteLine("A*B");
// Operation(delegate(int a, int b) { return a * b; });
// Console.Read(); //2 代理
Console.WriteLine("A+B");
TwoInt32OperationDel t = new TwoInt32OperationDel(twoInt32Plus);
TwoInt32OperationDel t2 = new TwoInt32OperationDel(twoInt32Multi);
Operation(t);
Console.WriteLine("A*B");
Operation(t2);
Console.Read(); ////3 Lambda方法调用
//Console.WriteLine("A+B");
//Operation((a, b) => { return a + b; });
//Console.WriteLine("A*B");
//Operation((a, b) => { return a * b; });
//Console.Read();
}
}
}

事件的使用:

       public delegate int plusDelegate(int a,int b);
public event plusDelegate pl;
public int plus(int a, int b)
{
return a + b;
}
private void button7_Click(object sender, EventArgs e)
{
pl += plus;
textBox3.Text = pl(, ).ToString();
}

委托的使用:

 public delegate int plusDelegate(int a,int b);
public int plus(int a, int b)
{
return a + b;
} private void button7_Click(object sender, EventArgs e)
{
plusDelegate p = new plusDelegate(plus);//方法1
plusDelegate p = (int a, int b) => { return a + b; };//方法2
plusDelegate p = delegate(int a, int b) { return (a + b); };//方法3 textBox3.Text = p(, ).ToString();
}
上一篇:关于iOS自定义UITabBar的几种方法


下一篇:如何实现 iOS 自定义状态栏