我如何用C#制作我自己的事件?

推荐答案

下面是使用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();
        }
    }
}

.net相关问答推荐

IANA 到 Windows 时区映射

作者主签名的时间戳发现了一个建链问题:UntrustedRoot: self-signed certificate in certificate chain

将客户端证书添加到 .NET Core HttpClient

如何从 HashSet 中检索实际项目?

为什么发布和调试模式下的代码行为不同?

无法加载文件或程序集“System.ValueTuple”

Nuget 连接try 失败“无法加载源的服务索引”

我可以先使用 EF 代码和 .net 核心生成迁移脚本吗

InvalidOperationException:无法解析类型“Microsoft.AspNetCore.Http.IHttpContextAccessor”的服务

Resharper Ctrl-T 映射丢失

Windows SDK 7.1 安装失败

判断 HttpStatusCode 是代表成功还是失败

EnsureSuccessStatusCode 的使用和它抛出的 HttpRequestException 的处理

String.Equals(a,b) 如何不产生 StackOverflowException?

如何从控制台应用程序中的 Task.WaitAll() 获取返回值?

在方法名称中使用“异步”后缀是否取决于是否使用了“异步”修饰符?

将 SignalR 2.0 .NET 客户端重新连接到服务器集线器的最佳实践

MongoDB C# 驱动程序 - 忽略绑定字段

为什么 HttpClient BaseAddress 不起作用?

从数据读取器填充数据表