如何在C#中创建自己的事件?


122

如何在C#中创建自己的事件?

Answers:


217

这是使用C#创建和使用事件的示例

using System;

namespace Event_Example
{
    //First we have to define a delegate that acts as a signature for the
    //function that is ultimately called when the event is triggered.
    //You will notice that the second parameter is of MyEventArgs type.
    //This object will contain information about the triggered event.
    public delegate void MyEventHandler(object source, MyEventArgs e);

    //This is a class which describes the event to the class that recieves it.
    //An EventArgs class must always derive from System.EventArgs.
    public class MyEventArgs : EventArgs
    {
        private string EventInfo;
        public MyEventArgs(string Text)
        {
            EventInfo = Text;
        }
        public string GetInfo()
        {
            return EventInfo;
        }
    }

    //This next class is the one which contains an event and triggers it
    //once an action is performed. For example, lets trigger this event
    //once a variable is incremented over a particular value. Notice the
    //event uses the MyEventHandler delegate to create a signature
    //for the called function.
    public class MyClass
    {
        public event MyEventHandler OnMaximum;
        private int i;
        private int Maximum = 10;
        public int MyValue
        {
            get
            {
                return i;
            }
            set
            {
                if(value <= Maximum)
                {
                    i = value;
                }
                else
                {
                    //To make sure we only trigger the event if a handler is present
                    //we check the event to make sure it's not null.
                    if(OnMaximum != null)
                    {
                        OnMaximum(this, new MyEventArgs("You've entered " +
                            value.ToString() +
                            ", but the maximum is " +
                            Maximum.ToString()));
                    }
                }
            }
        }
    }

    class Program
    {
        //This is the actual method that will be assigned to the event handler
        //within the above class. This is where we perform an action once the
        //event has been triggered.
        static void MaximumReached(object source, MyEventArgs e)
        {
            Console.WriteLine(e.GetInfo());
        }

        static void Main(string[] args)
        {
            //Now lets test the event contained in the above class.
            MyClass MyObject = new MyClass();
            MyObject.OnMaximum += new MyEventHandler(MaximumReached);

            for(int x = 0; x <= 15; x++)
            {
                MyObject.MyValue = x;
            }

            Console.ReadLine();
        }
    }
}

4
在访问了一百种解释之后,这终于帮助了我。SE是正确的,职位仍然适用历经数年。

1
{Meh!}我总是了写event课上的那一部分。
jp2code 2015年

51

我在活动文章中对活动和代表进行了全面的讨论。对于最简单的事件,您只需声明一个公共事件,编译器就会创建一个事件和一个字段来跟踪订户:

public event EventHandler Foo;

如果您需要更复杂的订阅/取消订阅逻辑,则可以明确地做到这一点:

public event EventHandler Foo
{
    add
    {
        // Subscription logic here
    }
    remove
    {
        // Unsubscription logic here
    }
}

1
我不确定如何从我的代码中调用该事件,但事实证明它确实很明显。您就像将其传递给sender和EventArgs对象的方法一样调用它。[即 如果(fooHappened)Foo(sender,eventArgs); ]
理查德·加赛德

2
@理查德:不完全;您需要处理没有订阅者的情况,因此委托引用将为null。
乔恩·斯基特

期待您链接的文章中有关线程安全事件的C#4更新。真的很棒,@ JonSkeet!
kdbanman 2015年

20

您可以使用以下代码声明事件:

public event EventHandler MyOwnEvent;

如果需要,可以使用自定义委托类型而不是EventHandler。

您可以在文章事件教程(MSDN)中找到有关在.NET中使用事件的详细信息/教程。


4

要做到这一点,我们必须知道三个组成部分

  1. 负责的地方 firing the Event
  2. 负责的地方 responding to the Event
  3. 活动本身

    一个。事件

    b。事件参数

    C。EventArgs枚举

现在让我们创建在调用函数时触发的事件

但是我按如下方式解决此问题的顺序是:在创建类之前,我正在使用该类

  1. 负责的地方 responding to the Event

    NetLog.OnMessageFired += delegate(object o, MessageEventArgs args) 
    {
            // when the Event Happened I want to Update the UI
            // this is WPF Window (WPF Project)  
            this.Dispatcher.Invoke(() =>
            {
                LabelFileName.Content = args.ItemUri;
                LabelOperation.Content = args.Operation;
                LabelStatus.Content = args.Status;
            });
    };

NetLog是静态类,我将在以后解释

下一步是

  1. 负责的地方 firing the Event

    //this is the sender object, MessageEventArgs Is a class I want to create it  and Operation and Status are Event enums
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Started));
    downloadFile = service.DownloadFile(item.Uri);
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Finished));

第三步

  1. 活动本身

我在名为NetLog的类中扭曲了Event

public sealed class NetLog
{
    public delegate void MessageEventHandler(object sender, MessageEventArgs args);

    public static event MessageEventHandler OnMessageFired;
    public static void FireMessage(Object obj,MessageEventArgs eventArgs)
    {
        if (OnMessageFired != null)
        {
            OnMessageFired(obj, eventArgs);
        }
    }
}

public class MessageEventArgs : EventArgs
{
    public string ItemUri { get; private set; }
    public Operation Operation { get; private set; }
    public Status Status { get; private set; }

    public MessageEventArgs(string itemUri, Operation operation, Status status)
    {
        ItemUri = itemUri;
        Operation = operation;
        Status = status;
    }
}

public enum Operation
{
    Upload,Download
}

public enum Status
{
    Started,Finished
}

这个类现在包含the EventEventArgsEventArgs Enumsthe function负责触发事件

很抱歉这么长时间回答


它们在此答案中的主要区别在于使事件成为静态事件,这使事件可以被接收而无需引用触发事件的对象。非常适合订阅来自多个独立控件的事件。
Radderz
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.