技术开发 频道

.NET中的委托:细节详解

       4 .NET中的事件委托

  举一个简单的例子,.NET中经常使用的控件Button,当我们把Button 控件 drap and drop到界面,然后双击界面的Button我们发现程序中自动生成了一个响应Button的事件方法,然后我们给事件方法添加Code之后,当我们点击该Button就响应该方法了,但我们没有看到代码中有任何的委托和事件之类的定义,其实这些.NET都已经做好了。我们可以查看如下文件。

                                                                     图2事件委托实现

  如上图所示我们打开Designer文件,事件委托的实现都在这里实现了。

  其中,EventHandler就是一个代理类型,可以认为它是一个“类”,是所有返回类型为void,具备两个参数分别是object sender和EventArgs e,第一个参数表示引发事件的控件,或者说它表示点击的那个按钮。通过以下的代码我们细细解析一下。

   

private void button1_Click(object sender, EventArgs e)
        {
            
//获取被点击Button的实例
            Button objBotton
= sender as Button;
            
if (objBotton != null)
            {
                objBotton.Text
= "Hello you click me.";
                objBotton.AutoSize
= true;
            }
            
else
            {
                
//Exception Handle.
            }

     

                             图3点击产生效果

  OK现在明白了sender就是传递一个被点击对象的实例,第二个参数名叫e的EventArgs参数,用于 表示附加的事件关联的事件信息。当点击按钮时,没有附加任何关联的事件信息,如上的点击事件,第二参数并不表示任何有用的信息。但什么时候会用到呢?

  我们先介绍一下EventArgs这个的类型。其实这个类并没有太多的功能,它主要是作为一个基类让其他类去实现具体的功能和定义,当我们搜索EventArgs发现很多类是继承于它的。

public class EventArgs
{   
             // Fields   
             public static readonly EventArgs Empty;    
            // Methods    static EventArgs();    
             public EventArgs();}

 

    举其中的ImageClickEventArgs为例,它继承于EventArgs,而且还添加了自己的字段用来基类X和Y的坐标值(这是一个ImageButton被点击时候响应的),然后获取该按钮的X和Y坐标。

 

                      图4获取ImageClickEventArgs关联点击坐标

  前面提到其他事件关联信息类型都是通过继承EventArgs实现的,所以说我们自己也可以自定义一个事件关联信息类型,如下我们只需继承EventArgs就OK了。 

/// <summary>
    
/// 自定义事件关联类
    
/// </summary>
    
public class ColorChangedEventArgs : EventArgs
    {
        
private Color color;

        
/// <summary>
        
/// Initializes a new instance of the <see cref="ColorChangedEventArgs"/> class.
        
/// </summary>
        
/// <param name="c">The c.</param>
        
public ColorChangedEventArgs(Color c)
        {
            color
= c;
        }

        
/// <summary>
        
/// Gets the color of the get.
        
/// </summary>
        
/// <value>
        
/// The color of the get.
        
/// </value>
        
public Color GetColor
        {
            
get { return color; }
        }

}
0
相关文章