Barotrauma Client Doc
NamedEvent.cs
1 using System;
2 using System.Collections.Generic;
3 
4 namespace Barotrauma
5 {
6  internal sealed class NamedEvent<T> : IDisposable
7  {
8  private readonly Dictionary<Identifier, Action<T>> events = new Dictionary<Identifier, Action<T>>();
9 
10  public void Register(Identifier identifier, Action<T> action)
11  {
12  if (HasEvent(identifier))
13  {
14  throw new ArgumentException($"Event with the identifier \"{identifier}\" has already been registered.", nameof(identifier));
15  }
16 
17  events.Add(identifier, action);
18  }
19 
20  public void RegisterOverwriteExisting(Identifier identifier, Action<T> action)
21  {
22  if (HasEvent(identifier))
23  {
24  Deregister(identifier);
25  }
26 
27  Register(identifier, action);
28  }
29 
30  public void Deregister(Identifier identifier)
31  {
32  events.Remove(identifier);
33  }
34 
35  public void TryDeregister(Identifier identifier)
36  {
37  if (!HasEvent(identifier)) { return; }
38  Deregister(identifier);
39  }
40 
41  public bool HasEvent(Identifier identifier) => events.ContainsKey(identifier);
42 
43  public void Invoke(T data)
44  {
45  foreach (var (_, action) in events)
46  {
47  action?.Invoke(data);
48  }
49  }
50 
51  public void Dispose()
52  {
53  events.Clear();
54  }
55  }
56 }