using System; using System.Collections.Generic; namespace MLEM.Misc { /// /// Represents an object that can hold generic key-value based data. /// A lot of MLEM components extend this class to allow for users to add additional data to them easily. /// This implemention uses an underlying that only keeps track of non-default values. /// public class GenericDataHolder : IGenericDataHolder { private static readonly string[] EmptyStrings = new string[0]; private Dictionary data; /// [Obsolete("This method will be removed in a future update in favor of the generic SetData.")] public void SetData(string key, object data) { this.SetData(key, data); } /// public void SetData(string key, T data) { if (EqualityComparer.Default.Equals(data, default)) { if (this.data != null) this.data.Remove(key); } else { if (this.data == null) this.data = new Dictionary(); this.data[key] = data; } } /// public T GetData(string key) { if (this.data != null && this.data.TryGetValue(key, out var val)) return (T) val; return default; } /// public IEnumerable GetDataKeys() { if (this.data == null) return GenericDataHolder.EmptyStrings; return this.data.Keys; } } /// /// Represents an object that can hold generic key-value based data. /// A lot of MLEM components extend this class to allow for users to add additional data to them easily. /// public interface IGenericDataHolder { /// /// Store a piece of generic data on this object. /// /// The key to store the data by /// The data to store in the object [Obsolete("This method will be removed in a future update in favor of the generic SetData.")] void SetData(string key, object data); /// /// Store a piece of generic data on this object. /// /// The key to store the data by /// The data to store in the object void SetData(string key, T data); /// /// Returns a piece of generic data of the given type on this object. /// /// The key that the data is stored by /// The type of the data stored /// The data, or default if it doesn't exist T GetData(string key); /// /// Returns all of the generic data that this object stores. /// /// The generic data on this object IEnumerable GetDataKeys(); } }