正如在其他答案中所说的,提出一个事件,您的GUI会显示您的日志文本。 这是一个完整的例子:
1)首先想想什么信息携带的事件和扩展EventArgs类的定义你参数事件类。我想揭露一个字符串,它是你的日志文本:
public class LogEventArgs : EventArgs
{
public string messageEvent {get;set;}
}
2)对于semplicity假设有暴露你想登录的业务方法的所有MyApplication类。我们将从这里定义并提出一个事件。日志记录将成为引发我们日志事件的私有方法。
public class MyApplication
{
public void BusinessMethod(){
this.Logging("first");
System.Threading.Thread.Sleep(1000);
this.Logging("second");
System.Threading.Thread.Sleep(3000);
this.Logging("third");
}
}
3)执行事件提升。为了处理一个事件,我们使用一个委托,它既是接收方(你的GUI)中必须实现什么方法声明以消耗该事件的描述,又是指向接收方法的指针。我们宣布事件OnLogging。 内部日志记录方法我们引发事件设置日志消息的参数。我们必须检查not null事件处理程序,因为如果没有该事件的侦听程序,则句柄将为null(指向接收方事件使用方法的空指针)。
public delegate void OnLoggingEventHandler(object sender, LogEventArgs e);
public event OnLoggingEventHandler OnLogging;
private void Logging(string message)
{
LogEventArgs logMessage = new LogEventArgs();
logMessage.messageEvent = message;
if (OnLogging != null)
{
OnLogging(this, logMessage);
}
}
4)现在我们必须实现一个事件监听器和一个使用它的方法。假设有一个带有启动应用程序业务方法的按钮的窗体窗体和一个显示日志消息的文本框。这是我们没有事件听众和消费者的形式。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MyApplication myApp = new MyApplication();
myApp.BusinessMethod();
}
}
5)我们定义了一个处理事件的消费者方法,在我们的文本框中写入由事件引发的日志消息。当然这个方法具有与委托相同的签名。
private void MyApplication_OnLogging(object sender, LogEventArgs e)
{
this.textBox1.AppendText(e.messageEvent + "\n");
}
6)使用C#本地运算符,我们将OnLogging事件绑定到事件使用者。
private void button1_Click(object sender, EventArgs e)
{
MyApplication myApp = new MyApplication();
myApp.OnLogging += new MyApplication.OnLoggingEventHandler(MyApplication_OnLogging);
myApp.BusinessMethod();
}
谢谢,LogDelegate是做什么的,OnLog事件是在哪里声明的? – systempuntoout 2011-02-15 07:42:35
@systempuntoout,日志委托只是事件的类型。 OnLog事件在该Logger类中声明。您的代码将创建此类的一个实例并将其公开。您的GUI代码会为“OnLog”事件添加一个处理程序并相应地进行处理。 – 2011-02-15 10:52:40
我编辑了你的代码以使其实际工作;)你忘记了将LogDelegate添加到事件中。 – Stormenet 2011-05-27 06:58:28