简体   繁体   中英

Why should I use a Messaging/Signal/Event library before simply System.Action in c#?

I Started developing projects using Unity that uses C#. I found tons of people recommending using libraries like https://github.com/yankooliveira/signals or http://wiki.unity3d.com/index.php/CSharpMessenger_Extended to control events like when a player hp changes, some currency changes, or whatever changes rarely in a none constant time rate.

The concept of events or signals is really powerful, but why not simply use System.Action combined with the event keyword? what advantages provide these libs?

public class SomeClass
{
    public static event Action OnSomethingChange;

    public void TriggerOnSomethingChange()
    {
        OnSomethingChange?.Invoke();
    }

    public void SubscribeToOnSomethingChange()
    {
        OnSomethingChange += OnSomethingChangeHandler;
    }

    public void UnsubscribeToOnSomethingChange()
    {
        OnSomethingChange -= OnSomethingChangeHandler;
    }

    private void OnSomethingChangeHandler()
    {
        
    }
}

Short

These libraries give you a generalization of your events and you don't need to write your own system.

A little bit more information

When you use only Action events with event key need to remember about params that you want to pass through events, because in this library is very simple, the only thing that needs - create own class with fields, but if use your own Actions or one Action with general params necessary to use Boxing/Unboxing or common fields.

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