黑马程序员技术交流社区
标题: 关于委托的最重要的作用 [打印本页]
作者: brucel50 时间: 2013-8-1 12:58
标题: 关于委托的最重要的作用
之前看视频说,委托最重要的作用就是实现代码的注入,那是不是说,被注入的代码所在的类中,一定有一个某委托类型的字段,与调用该字段.Invoke()(字段())的语句呢?
作者: 许庭洲 时间: 2013-8-1 18:05
本帖最后由 许庭洲 于 2013-8-1 18:06 编辑
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Declare a delegate
delegate void Del(int i, double j);
class MathClass
{
staticvoid Main()
{
MathClass m = new MathClass();
// Delegate instantiation using"MultiplyNumbers"
Del d = m.MultiplyNumbers;
//Invoke the delegate object.
System.Console.WriteLine("Invoking the delegate using'MultiplyNumbers':");
for (int i = 1; i <= 5; i++)
{
d(i, 2);
}
}
//Declare the associated method.
voidMultiplyNumbers(int m, double n)
{
System.Console.Write(m * n + " ");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
输出
Invoking the delegate using 'MultiplyNumbers':
2 4 6 8 10
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
作者: lvjayj 时间: 2013-8-1 21:39
楼上的例子很好哇。
delegate int Operand(int a, int b); //第一步:委托声明
class Class1
{
static void Main(string[]args)
{
Class1 c1 = new Class1();
Operand ope = new Operand(c1.Add);
//委托实例化,注意参数是要使用的参数名,且不带括号
Console.WriteLine(ope(10, 20)); //委托调用,调用委托的方法用
委托的对象加参数
Console.ReadLine();
}
//定义一个方法,求两个加数的和
private int Add(int num1, int num2)
{
return (num1 + num2);
}
}
托分三个步骤:
1、委托声明。2、委托实例化。3、委托调用。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |