您的位置:首页 > 其它

自定义委托,事件,参数的简单随笔

2010-03-08 17:21 465 查看
.Net Framework的编码规范:

委托类型的名称都应该以EventHandler结束。
委托的原型定义:有一个void返回值,并接受两个输入参数:一个Object 类型,一个 EventArgs类型(或继承自EventArgs)。
继承自EventArgs的类型应该以EventArgs结尾。

event本身是C#在委托基础上封装一些用于多事件注册的机制,这是event和委托的区别,委托仅仅是控件类定义和用户自定义事件方法共同遵守的方法的contract契约,一个方法类型而已 。

using System;
using System.Collections.Generic;
using System.Text;

namespace DelegateApplication
{
class Program
{
static void Main(string[] args)
{
string str = "show !!!";
InitEvent(str);
Console.ReadLine();
}
private static void InitEvent(string showStr)
{
//初始化事件参数类,赋值
InformationEventArgs eventArgs = new InformationEventArgs();
eventArgs.Information = showStr;

InformationEvent eventer = new InformationEvent();
InformationCall call = new InformationCall();

eventer.InformationClick+= new InformationHandler(call.ShowInformation);

eventer.OnInformation(eventArgs);
Console.ReadLine();
}
}
/// <summary>
/// 事件参数
/// </summary>
public class InformationEventArgs : EventArgs
{
private string _message;
public string Information
{
get
{
return _message;
}
set
{
_message = value;
}
}
}
//委托
public delegate void InformationHandler(object sender,InformationEventArgs e);
//事件
public class InformationEvent
{
public event InformationHandler InformationClick;
//触发事件
public void OnInformation(InformationEventArgs e)
{
if (InformationClick != null)
{
InformationClick(this, e);//匹配委托 进行InformationEventArgs传值
}
}
}

public class InformationCall
{
private string _strInformation;
public string InformationString
{
get
{
return _strInformation;
}
set
{
_strInformation = value;
}
}
//调用的方法 匹配委托 显示事件参数的值
public void ShowInformation(object sender, InformationEventArgs e)
{
InformationString = e.Information;
Console.WriteLine(InformationString);
}
}
}

源代码:/Files/jasenkin/DelegateApplication.rar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: