// Copyright (c) ppy Pty Ltd . Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; namespace osu.Game.Context { public abstract class ContextContainer { /// /// The contexts of this container. /// The objects always have the type of their key. /// private readonly Dictionary contexts; protected ContextContainer() { contexts = new Dictionary(); } /// /// Checks whether this object has the context with type T. /// /// The type to check the context of. /// Whether the context object with type T exists in this object. public bool HasContext() where T : IContext { return contexts.ContainsKey(typeof(T)); } /// /// Gets the context with type T. /// /// The type to get the context of. /// If the context does not exist in this hit object. /// The context object with type T. public T GetContext() where T : IContext { return (T)contexts[typeof(T)]; } /// /// Tries to get the context with type T. /// /// The found context with type T. /// The type to get the context of. /// Whether the context exists in this object. public bool TryGetContext(out T context) where T : IContext { if (contexts.TryGetValue(typeof(T), out var context2)) { context = (T)context2; return true; } context = default!; return false; } /// /// Sets the context object of type T. /// /// The context type to set. /// The context object to store in this object. public void SetContext(T context) where T : IContext { contexts[typeof(T)] = context; } /// /// Removes the context of type T from this object. /// /// The type to remove the context of. /// Whether a context was removed. public bool RemoveContext() where T : IContext { return RemoveContext(typeof(T)); } /// /// Removes the context of type T from this object. /// /// The type to remove the context of. /// Whether a context was removed. public bool RemoveContext(Type t) { return contexts.Remove(t); } } }