Temptation

寻道之路 , 与您同行 !

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  321 随笔 :: 0 文章 :: 171 评论 :: 3 Trackbacks
1.委托是什么?可以理解为对象的一种新的类型,类似于 C 或 C++ 中的函数指针。
2.什么时候使用委托?把方法传送给其他方法的时候使用它。
    我们知道方法的参数主要用于传递数据,比如: int I = int.Parse("99"),其中调用了System.Int32类的静态方法Parse()。那么把一个方法在作为参数传给另一个方法,怎么传呢?
    最简单的途径就是把方法名作为参数传递给其他的方法。C#规定,如果要传递方法,必须把方法的细节封装在一种新的类型对象中,即委托。使用委托可以将方法引用封装在委托对象内,然后可以将该委托对象传递给可调用所引用方法的代码,而不必在编译时知道将调用哪个方法。
    委托对象的一个有用属性是,它们可以:
    “+”运算符用来组合。组合的委托可调用组成它的那两个委托。只有相同类型的委托才可以组合。
    “-”运算符用来从组合的委托移除组件委托。
例:
using System;

delegate void MyDelegate( string s );

class MyClass
{
    public static void Hello( string s )
    {
        Console.WriteLine( "  Hello, {0}!", s );
    }

    public static void Goodbye( string s )
    {
        Console.WriteLine( "  Goodbye, {0}!", s );
    }

    public static void Main( )
    {
        MyDelegate a, b, c, d;
       
        // Create the delegate object a that references
        // the method Hello:
        a = new MyDelegate( Hello );
        // Create the delegate object b that references
        // the method Goodbye:
        b = new MyDelegate( Goodbye );
        // The two delegates, a and b, are composed to form c:
        c = a + b;
        // Remove a from the composed delegate, leaving d,
        // which calls only the method Goodbye:
        d = c - a;
       
        Console.WriteLine( "Invoking delegate a:" );
        a( "A" );
        Console.WriteLine( "Invoking delegate b:" );
        b( "B" );
        Console.WriteLine( "Invoking delegate c:" );
        c( "C" );
        Console.WriteLine( "Invoking delegate d:" );
        d( "D" );
    }
}
输出
Invoking delegate a:
Hello, A!
Invoking delegate b:
Goodbye, B!
Invoking delegate c:
Hello, C!
Goodbye, C!
Invoking delegate d:
Goodbye, D!

posted on 2006-04-07 11:22 temptation 阅读(76) 评论(0)  编辑 收藏 所属分类: C#技术

标题  
姓名  
主页
Email (只有博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      


相关链接: