Delegate vs. delegate keyword

前端 未结 6 2069
长情又很酷
长情又很酷 2020-12-13 03:51

If you like to create custom delegates you would use the delegate keyword in lowercase.

What can you do with the actual Delegate Class? Wh

6条回答
  •  旧时难觅i
    2020-12-13 04:27

    The delegate keyword is for the compiler to do some magic for you. When you declare a new delegate with a custom signature,

    • the compiler creates a new Type for you derived from MulticastDelegate (which in turn derives from Delegate).
    • the compiler adds an Invoke method with your custom signature
    • similarly the compiler adds BeginInvoke and EndInvoke methods for this new type

    So now when you call delObject(args) - the compiler translates that to delObject.Invoke(args)

    The Delegate base class provides some functionality such as

    1. CreateDelegate (for obtaining a delegate wrapping a static/instance method)
    2. DynamicInvoke (to invoke a delegate with a list of arguments - late bound)
    3. Combine and Remove (for delegate chaining.. chain multiple delegates together e.g. multiple event handler delegates for an event)

    The C# compiler forbids you from deriving from Delegate explcitly in your code.. you have to use the delegate keyword.

提交回复
热议问题