65.9K
CodeProject 正在变化。 阅读更多。
Home

创建高级C#自定义事件

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.42/5 (56投票s)

2005年1月20日

viewsIcon

223560

downloadIcon

2455

使用委托事件连接 C# 对象。

引言

将自定义事件及其参数挂接到对象。

在本文中,我将尝试说明如何将自定义事件挂接到一个对象。我们将深入一些,并创建我们自己的事件参数,这些参数是从 EventArgs 基类派生的。

如您将在代码中看到,有一个 item 对象,它指的是一个库存项目。当它具有有效的发货跟踪号时,我们的对象将引发一个事件。

让我们看一下使用我们 item 对象的主程序

using System;
namespace EventExample
{
    class Class1
    {
        static void Main(string[] args)
        {
            // we will create our instance
            Shipment myItem = new Shipment();

            // we need to add the delegate event to new object
            myItem.OnShipmentMade += 
                   new Shipment.ShipmentHandler(ShowUserMessage);

            // we assumed that the item has been just shipped and 
            // we are assigning a tracking number to it.
            myItem.TrackingNumber = "1ZY444567";

            // The common procedure to see what is going on the 
            // console screen
            Console.Read();
        }
       
        static void ShowUserMessage(object a, ShipArgs e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

现在看一下我们的自定义事件类

using System;
namespace EventExample
{
    public class ShipArgs : EventArgs
    {
        private string message;

        public ShipArgs(string message)
        {
            this.message = message;
        }

        // This is a straightforward implementation for 
        // declaring a public field
        public string Message
        {
            get
            {
                return message;
            }
        }
    }
}

最后,这是对象

using System;
namespace EventExample
{
    public class Shipment
    {
        private string trackingnumber;

        // The delegate procedure we are assigning to our object
        public delegate void ShipmentHandler(object myObject, 
                                             ShipArgs myArgs);

        public event ShipmentHandler OnShipmentMade;

        public string TrackingNumber
        {
            set
            {
                trackingnumber = value;

                // We need to check whether a tracking number 
                // was assigned to the field.
                if (trackingnumber.Length != 0)
                {
                    ShipArgs myArgs = new ShipArgs("Item has been shipped.");

                    // Tracking number is available, raise the event.
                    OnShipmentMade(this, myArgs);
                }
            }
        }

        public Shipment()
        {
        }
    }
}
© . All rights reserved.