对委托delegate 的一些理解

设计模式 第4章《在C#中使用类和对象》
代理就是指针函数,本质上是对另一个类中函数的引用,可以分派和使用函数无须知道函数来自与那一个类

1 委托delegate
private delegate string fTxDelegate(string s);    //declare delegate
        fTxDelegate ftx;  //instance of delegate

2类Capital定义
using System;

namespace Delegate
{
    
/// <summary>
    
/// contains a method that converts to uppercase
    
/// </summary>

    public class Capital
    
{
        
public string fixText(string s) {
            
return s.ToUpper ();
        }

    }

}

3类Lower定义
using System;

namespace Delegate
{
    
/// <summary>
    
/// contains a static method to convert to lowercase
    
/// </summary>

    public class Lower
    
{
        
public static string fixText(string s) {
            
return s.ToLower();
        }

    }

}

4委托的使用
private void opCap_CheckedChanged(object sender, System.EventArgs e) {
            btProcess.Enabled 
=true;
            
//assign an instance method to the delegate
            
//create an instance of the Capital class
            ftx = new fTxDelegate (new Capital().fixText);
        }

        
//-----
        private void opLower_CheckedChanged(object sender, System.EventArgs e) {
            btProcess.Enabled 
=true;
            
//assign a static method to the delegate
            
//the Lower class has a static method fixText
            ftx = new fTxDelegate (Lower.fixText);
        }


        
private void btProcess_Click(object sender, System.EventArgs e) {
            lsBox.Items.Add ( ftx(txName.Text ));
        }

posted @ 2006-11-28 17:25  jhtchina  阅读(284)  评论(0)    收藏  举报