using System; using System.Collections.Generic; using System.Runtime.Serialization; 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. /// [DataContract] public class GenericDataHolder : IGenericDataHolder { private static readonly string[] EmptyStrings = new string[0]; [DataMember(EmitDefaultValue = false)] private Dictionary data; /// public void SetData(string key, object data) { if (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 void SetData(string key, object 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(); } }