feat: IConfiguration for system and other configurations
This commit is contained in:
50
Engine.Core/Config/BasicConfiguration.cs
Normal file
50
Engine.Core/Config/BasicConfiguration.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Engine.Core.Config;
|
||||
|
||||
public class BasicConfiguration : IConfiguration
|
||||
{
|
||||
public Event<IConfiguration, IConfiguration.ConfigUpdateArguments> OnAdded { get; } = new();
|
||||
public Event<IConfiguration, IConfiguration.ConfigUpdateArguments> OnSet { get; } = new();
|
||||
public Event<IConfiguration, IConfiguration.ConfigUpdateArguments> OnRemoved { get; } = new();
|
||||
|
||||
private readonly Dictionary<string, object?> values = [];
|
||||
|
||||
public IReadOnlyDictionary<string, object?> Values => values;
|
||||
|
||||
public T? Get<T>(string key, T? defaultValue = default)
|
||||
{
|
||||
if (!values.TryGetValue(key, out object? value))
|
||||
return defaultValue;
|
||||
|
||||
if (value is T castedObject)
|
||||
return castedObject;
|
||||
|
||||
try { return (T?)System.Convert.ChangeType(value, typeof(T)); } catch { }
|
||||
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
public object? Get(string key)
|
||||
{
|
||||
values.TryGetValue(key, out object? value);
|
||||
return value;
|
||||
}
|
||||
|
||||
public bool Has(string key) => values.ContainsKey(key);
|
||||
|
||||
public void Remove<T>(string key)
|
||||
{
|
||||
if (values.Remove(key))
|
||||
OnRemoved.Invoke(this, new(key));
|
||||
}
|
||||
|
||||
public void Set<T>(string key, T value)
|
||||
{
|
||||
if (!values.TryAdd(key, value))
|
||||
values[key] = value;
|
||||
else
|
||||
OnAdded.Invoke(this, new(key));
|
||||
OnSet.Invoke(this, new(key));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user