c# delegate ,event

來源:互聯網
上載者:User

標籤:void   hand   get   string   line   appear   tar   prot   close   

首先說明,event其實也是一種delegate,為了區分,我們稱一般的delegate為“plain delegate”。

寫代碼的過程中,經常會在delegate和event之間進行選擇,以前也沒仔細思考選擇的原因,今天終於忍不住花了半天時間仔細琢磨了一下……好了,直接拿代碼說話吧:

using System;

namespace EventAndDelegate
{
    public delegate void TestDelegate(string s);

    public interface ITest {
        // 【區別】 1. event可以用在interface中,而plain delegate不可以(因為它是field)
        event TestDelegate TestE;   // Passed
        TestDelegate TestD;         // Error: Interfaces cannot contain fields
    }

    public class Parent {
        public event TestDelegate TestE;
        public TestDelegate TestD;

        protected void RaiseTestE(string s)
        {
            TestE(s);   // The event ‘EventAndDelegate.Parent.TestE‘ can only
                        // be used from within the type ‘EventAndDelegate.Parent‘
        }
    }

    public class Child : Parent {
        void ChildFunc()
        {
            // 【區別】 2. event不允許在聲明它的class之外(即使是子類)被調用(除此之外只能用於+=或-=),而plain delegate則允許
            TestD("OK");        // Passed
            TestE("Failure");   // Error: The event ‘EventAndDelegate.Parent.TestE‘ can only appear on
                                //        the left hand side of += or -= (except when used from within
                                //        the type ‘EventAndDelegate.Parent‘)

            // 【補充】 在子類中要觸發父類聲明的event,通常的做法是在父類中聲明一個protected的Raisexxx方法供子類調用
            RaiseTestE("OK");   // The class ‘EventAndDelegate.Child‘ can only call the
                                // ‘EventAndDelegate.ParentRaiseTestE‘ method to raise the event
                                // ‘EventAndDelegate.Parent.TestE‘

            // 【區別】 同2#
            object o1 = TestD.Target;
            object o2 = TestE.Target;   // The class ‘EventAndDelegate.Child‘ can only call the
                                        // ‘EventAndDelegate.ParentRaiseTestE‘ method to raise the event
                                        // ‘EventAndDelegate.Parent.TestE‘

            // 【區別】 同2#
            TestD.DynamicInvoke("OK");
            TestE.DynamicInvoke("OK");   // The class ‘EventAndDelegate.Child‘ can only call the
                                        // ‘EventAndDelegate.ParentRaiseTestE‘ method to raise the event
                                        // ‘EventAndDelegate.Parent.TestE‘
        }
    }

    class Other
    {
        static void Main(string[] args)
        {
            Parent p = new Parent();

            p.TestD += new TestDelegate(p_Test1);   // Passed
            p.TestE += new TestDelegate(p_Test1);   // Passed

            // 【區別】 3. event不允許使用賦值運算子,而plain delegate則允許。
            //             注意,對plain delegate,使用賦值運算子意味著進行了一次替換操作!
            p.TestD = new TestDelegate(p_Test2);   // Passed
            p.TestE = new TestDelegate(p_Test2);   // Error: The event ‘EventAndDelegate.Parent.TestE‘ can only appear on
                                                   //        the left hand side of += or -= (except when used from within
                                                   //        the type ‘EventAndDelegate.Parent‘)

            // 【區別】 同2#
            p.TestD("OK");      // Passed
            p.TestE("Failure"); // Error: The event ‘EventAndDelegate.Parent.TestE‘ can only appear on
                                //        the left hand side of += or -= (except when used from within
                                //        the type ‘EventAndDelegate.Parent‘)
        }

        static void p_Test1(string s)
        {
            Console.WriteLine("p_Test1: " + s);
        }

        static void p_Test2(string s)
        {
            Console.WriteLine("p_Test2: " + s);
        }
    }
}

 


分析:

  1. plain delegate與event的關係類似於field與Property(實事上前者就是field,或者我們可以把event看成是一種特殊的Property)
  2. 正是由於1#,在使用上,plain delegate幾乎沒有任何限制,而event則有嚴格的限制(只能用在+=和-=的左邊)

結論

    1. event更物件導向一些。
    2. 當我們需要靈活時,直接使用plain delegate;反之,需要嚴格的控制時,使用event。
    3. 由於event不能使用賦值運算子,因此有時我們要求一個事件在任何時刻只能有一個回應程式法時,我們使用plain delegate更為方便。 

c# delegate ,event

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.