简体   繁体   中英

Calling event of another class

I am new to C# and programming in general and am trying to figure out how to use events. Previously I have been programming with ActionScript3, and there events are a special class that you inherit from if you want to create your own events, and then that event can be called by any other class.

With C# I have tried to do something similar, like so:

public class EventManager
{
    public delegate void TempDelegate();
    public static event TempDelegate eSomeEvent;
}

public class SomeOtherClass
{
    //doing some stuff, then:
    if (EventManager.eSomeEvent != null)
    {
        EventManager.eSomeEvent();
    }
}

This gives me a compiler error CS0070: The event 'EventManager.eSomeEvent' can only appear on the left hand side of += or -= (except when used from within the type 'EventManager')

The information about this error over on the msdn indicates that I should use += instead of trying to call the event, but I don't really understand this. I'm not trying to subscribe anything from SomeOtherClass to the event delegate, I am just trying to call this event so that it starts executing those functions that are already subscribed to that event.

So is it possible to do it this way? If not, is it at all possible to call an event that is of one class, from another class? I simply wish to reuse certain events in my classes rather than creating many similar ones in multiple classes.

Any advice with this would be greatly appreciated!

You can wrap the event call in a public method and use that from your other classes.

public void OnSomeEvent()
{
    var handler = eSomeEvent;
    if (handler != null) handler(this, null);
}

However you might want to look at the design again, if you are really sure the event should be on a different class than the one triggering it.

Well, the typical solution is to put eSomeEvent invocation into the EventManager class

public class EventManager
{
    public delegate void TempDelegate();
    public static event TempDelegate eSomeEvent;

    // Not thread safe as well as your code
    // May be internal, not public is better (if SomeOtherClass is in the same namespace) 
    public static void PerformSomeEvent() {
      if (!Object.ReferenceEquals(null, eSomeEvent)) 
        eSomeEvent(); // <- You can do it here
    }
}

public class SomeOtherClass
{
    //doing some stuff, then:
    EventManager.PerformSomeEvent();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM