using System;
using System.Collections.Generic;
using SoftCircuits.Collections;
using UnityEngine;
namespace SLSFramework.General
{
public static class DictionaryExtension
{
///
/// 修改字典中指定键的值,如果键不存在则添加该键值对。
///
public static void ModifyOrAdd(this IDictionary dictionary, string key, float delta, float defaultValue = 0)
{
if (!dictionary.TryAdd(key, defaultValue + delta))
{
dictionary[key] += delta;
}
}
///
/// 从字典中获取指定键的原始值。
///
public static float GetRawValue(this Dictionary dictionary, string key, float defaultValue = 0)
{
return dictionary.GetValueOrDefault(key, defaultValue);
}
///
/// 从字典中获取指定键的值,并将其四舍五入为整数返回。
///
public static int GetRoundValue(this Dictionary dictionary, string key, int defaultValue = 0)
{
return dictionary.TryGetValue(key, out float value) ? Mathf.RoundToInt(value) : defaultValue;
}
///
/// 从字典中获取指定键的值,并将其向下取整为整数返回。
///
public static int GetFloorValue(this Dictionary dictionary, string key, int defaultValue = 0)
{
return dictionary.TryGetValue(key, out float value) ? Mathf.FloorToInt(value) : defaultValue;
}
///
/// 将源字典中的所有键值对粘贴到目标字典中,避免重复键。
///
public static void Paste(this IDictionary source, IDictionary target)
{
foreach (var pair in source)
{
if (!target.ContainsKey(pair.Key))
{
target[pair.Key] = pair.Value;
}
else
{
Debug.LogWarning($"Attribute \"{pair.Key}\" already exists. Skipping duplicate.");
}
}
}
}
public static class DictionaryExtensionForEvents
{
#region 不含返回值的事件
public static void Invoke(this IDictionary dictionary)
{
foreach (var action in dictionary.Values)
{
action.Invoke();
}
}
public static void Invoke(this IDictionary> dictionary, T arg)
{
foreach (var action in dictionary.Values)
{
action.Invoke(arg);
}
}
public static void Invoke(this IDictionary> dictionary, T0 arg0, T1 arg1)
{
foreach (var action in dictionary.Values)
{
action.Invoke(arg0, arg1);
}
}
public static void Invoke(this IDictionary> dictionary, T0 arg0, T1 arg1, T2 arg2)
{
foreach (var action in dictionary.Values)
{
action.Invoke(arg0, arg1, arg2);
}
}
#endregion
#region 含有返回值的事件
public static Dictionary Invoke(this IDictionary> dictionary)
{
var results = new Dictionary();
foreach (var pair in dictionary)
{
results[pair.Key] = pair.Value.Invoke();
}
return results;
}
public static Dictionary Invoke(this IDictionary> dictionary, T arg)
{
var results = new Dictionary();
foreach (var pair in dictionary)
{
results[pair.Key] = pair.Value.Invoke(arg);
}
return results;
}
public static Dictionary Invoke(this IDictionary> dictionary, T0 arg0, T1 arg1)
{
var results = new Dictionary();
foreach (var pair in dictionary)
{
results[pair.Key] = pair.Value.Invoke(arg0, arg1);
}
return results;
}
public static Dictionary Invoke(this IDictionary> dictionary, T0 arg0, T1 arg1, T2 arg2)
{
var results = new Dictionary();
foreach (var pair in dictionary)
{
results[pair.Key] = pair.Value.Invoke(arg0, arg1, arg2);
}
return results;
}
#endregion
}
}