A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© brucel50 中级黑马   /  2013-8-1 12:58  /  1339 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

之前看视频说,委托最重要的作用就是实现代码的注入,那是不是说,被注入的代码所在的类中,一定有一个某委托类型的字段,与调用该字段.Invoke()(字段())的语句呢?

评分

参与人数 1技术分 +1 收起 理由
赵宗荣 + 1

查看全部评分

2 个回复

倒序浏览
本帖最后由 许庭洲 于 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
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
回复 使用道具 举报
楼上的例子很好哇。

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、委托调用。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马