Files
lux/EgwCoreLib.Lux.Core/ParamDictFlex.cs
T
2026-03-27 12:23:13 +01:00

61 lines
1.8 KiB
C#

public class ParamDictFlex<TValue>
{
private Dictionary<string, TValue> DictVals { get; set; } = new Dictionary<string, TValue>();
// Costruttore da stringa JSON (TValue è un tipo concreto serializzabile)
public ParamDictFlex(string rawVal)
{
if (string.IsNullOrWhiteSpace(rawVal))
{
DictVals = new Dictionary<string, TValue>();
return;
}
DictVals = JsonConvert.DeserializeObject<Dictionary<string, TValue>>(rawVal)
?? new Dictionary<string, TValue>();
}
// Costruttore da dizionario
public ParamDictFlex(Dictionary<string, TValue> newDict)
{
DictVals = newDict ?? new Dictionary<string, TValue>();
}
// Versione serializzata del dizionario
public string Serialized
{
get => JsonConvert.SerializeObject(DictVals);
}
// Recupera valore; ritorna default(TValue) se la chiave non esiste
public TValue GetVal(string reqKey)
{
if (reqKey is null) throw new ArgumentNullException(nameof(reqKey));
return DictVals.TryGetValue(reqKey, out var val) ? val : default!;
}
// Imposta valore (aggiunge o aggiorna)
public void SetVal(string key, TValue val)
{
if (key is null) throw new ArgumentNullException(nameof(key));
DictVals[key] = val;
}
// Rimuove chiave
public bool Remove(string key)
{
if (key is null) throw new ArgumentNullException(nameof(key));
return DictVals.Remove(key);
}
// Controlla esistenza chiave
public bool ContainsKey(string key)
{
if (key is null) throw new ArgumentNullException(nameof(key));
return DictVals.ContainsKey(key);
}
// Espone una copia di sola lettura del dizionario
public IReadOnlyDictionary<string, TValue> AsReadOnly() => new Dictionary<string, TValue>(DictVals);
}