How to reference an event in C#

后端 未结 3 2022
陌清茗
陌清茗 2020-12-18 00:17

I have the following class, which has one public event called LengthChanged:

class Dimension
{
    public int Length
    {
        get
        {         


        
相关标签:
3条回答
  • 2020-12-18 01:00

    Unfortunately there isn't really a way of doing this. Events aren't first class citizens in .NET in general - although F# tries to promote them there.

    Either pass in the subscribe/unsubscribe delegate or using a string indicating the name of the event. (The latter is often shorter, but obviously less safe at compile-time.)

    Those are the approaches which Reactive Extensions takes - if there were a cleaner way of doing it, I'm sure they would be using that :(

    0 讨论(0)
  • 2020-12-18 01:14

    Event is not supposed to be passed into another method. However, you can pass delegate into another method. Perhaps, what you are looking for are just a simple public delegate instead of event.

    If you change your event to this

    public System.EventHandler LengthChanged; 
    

    You can simply pass the LengthChanged to Observer like this

    Foo foo = ...;
    Dimension dim = ...;
    foo.Observer (dim.LengthChanged); 
    
    0 讨论(0)
  • 2020-12-18 01:16

    You can create a custom Accessor.

       public event EventHandler NewEvent
                {
                    add { Dimension.LengthChanged += value; }
                    remove { Dimension.LengthChanged -= value; }
                }
    

    Please See https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/events/how-to-implement-custom-event-accessors

    0 讨论(0)
提交回复
热议问题