C# 自訂事件並使用自訂事件參數方法

來源:互聯網
上載者:User
C# 自訂帶自訂參數的事件方法

C# 自訂帶自訂參數的事件 需要經過以下幾個步驟:
  1、自訂事件參數   :要實現自訂參數的事件,首先要自訂事件參數。該參數是個類。繼承自EventArgs。
  2、聲明委託用於事件  
  3、聲明事件
  4、定義事件觸發    :事件定義後,要有個觸發事件的動作。
  以上基本上完成了自訂事件。不過還缺事件調用,請看下邊兩個步驟。

  5、事件觸發

  6、自己編寫事件的處理 :事件觸發後。要處理事件。 

實現:

  假設有個列印對象,需要給它自訂一個列印事件。事件參數中傳入列印的份數。在程式載入時,調用列印對象,並通過自訂列印參數,實現列印。

  代碼如下,此代碼是在WinForm下編寫。

 

        //列印對象
        public class CustomPrint
        {
            /// <summary>
            ///  1、定義事件參數
            /// </summary>
            public class CustomPrintArgument : EventArgs
            {
                private int copies;
                public CustomPrintArgument(int numberOfCopies)
                {
                    this.copies = numberOfCopies;
                }
                public int Copies
                {
                    get { return this.copies; }
                }
            }

            /// <summary>
            /// 2、聲明事件的委託
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            public delegate void CustomPrintHandler(object sender, CustomPrintArgument e);

            /// <summary>
            /// 3、聲明事件
            /// </summary>
            public event CustomPrintHandler CustomPrintEvent;

            /// <summary>
            /// 4、定義觸發事件
            /// </summary>
            /// <param name="copyies">份數</param>
            public void RaisePrint(int copyies)
            {
                CustomPrintArgument e = new CustomPrintArgument(copyies);
                CustomPrintEvent(this, e);
            }
        }

        /// <summary>
        /// WinForm 建構函式
        /// </summary>
        public Form1()
        {
            InitializeComponent();

            PrintCustom();
        }

        /// <summary>
        /// 列印方法
        /// </summary>
        private void PrintCustom()
        {
            //執行個體對象
            CustomPrint cp = new CustomPrint();

            //添加事件
            cp.CustomPrintEvent += new CustomPrint.CustomPrintHandler(cp_CustomPrintEvent);

            //5、觸發事件
            cp.RaisePrint(10);

        }

        //6、事件處理
        void cp_CustomPrintEvent(object sender, CustomPrint.CustomPrintArgument e)
        {
            int copies = e.Copies;
            MessageBox.Show(copies.ToString());
        }
    }

  運行程式,在快顯視窗中會顯示10。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.