如何在C#中编写事件和事件处理程序?

时间:2022-10-30 07:23:45

I've been trying a good way to memorize how to write events and eventhandlers in C# for a while. Whenever I want to refer to a tutorial on the Internet they tend to be verbose.

我一直在尝试记住如何在C#中编写事件和事件处理程序一段时间。每当我想在互联网上引用教程时,他们往往都很冗长。

The question is how do I write events and eventhandlers in C#? Have you got a code example that illustrates easily how to write such?

问题是如何在C#中编写事件和事件处理程序?你有一个代码示例,很容易说明如何写这样的?

2 个解决方案

#1


They don't have to be verbose:

它们不必冗长:

// declare an event:
public event EventHandler MyEvent;

// raise an event:
var handler = MyEvent;
if(handler != null) handler(this, EventArgs.Empty);

// consume an event with an anon-method:
obj.MyEvent += delegate { Console.WriteLine("something happened"); };

// consume an event with a named method:
obj.MyEvent += SomeHandler;

void SomeHandler(object sender, EventArgs args) {
    Console.WriteLine("something happened");
}

What is the bit that is being troublesome?

什么是麻烦的?

#2


Once you get an appetite, try this out:

一旦你胃口大开,试试这个:

For VS2005: How to: Publish Events that Conform to .NET Framework Guidelines (C# Programming Guide) http://msdn.microsoft.com/en-us/library/w369ty8x(v=vs.80).aspx

对于VS2005:如何:发布符合.NET Framework准则的事件(C#编程指南)http://msdn.microsoft.com/en-us/library/w369ty8x(v=vs.80).aspx

For Visual Studio 11: http://msdn.microsoft.com/en-us/library/w369ty8x(v=vs.110).aspx

对于Visual Studio 11:http://msdn.microsoft.com/en-us/library/w369ty8x(v = vs.110).aspx

#1


They don't have to be verbose:

它们不必冗长:

// declare an event:
public event EventHandler MyEvent;

// raise an event:
var handler = MyEvent;
if(handler != null) handler(this, EventArgs.Empty);

// consume an event with an anon-method:
obj.MyEvent += delegate { Console.WriteLine("something happened"); };

// consume an event with a named method:
obj.MyEvent += SomeHandler;

void SomeHandler(object sender, EventArgs args) {
    Console.WriteLine("something happened");
}

What is the bit that is being troublesome?

什么是麻烦的?

#2


Once you get an appetite, try this out:

一旦你胃口大开,试试这个:

For VS2005: How to: Publish Events that Conform to .NET Framework Guidelines (C# Programming Guide) http://msdn.microsoft.com/en-us/library/w369ty8x(v=vs.80).aspx

对于VS2005:如何:发布符合.NET Framework准则的事件(C#编程指南)http://msdn.microsoft.com/en-us/library/w369ty8x(v=vs.80).aspx

For Visual Studio 11: http://msdn.microsoft.com/en-us/library/w369ty8x(v=vs.110).aspx

对于Visual Studio 11:http://msdn.microsoft.com/en-us/library/w369ty8x(v = vs.110).aspx