87 lines
3.1 KiB
C#
87 lines
3.1 KiB
C#
using System.Reflection;
|
|
using JNPF.DependencyInjection;
|
|
|
|
namespace JNPF.Common.Extension;
|
|
|
|
/// <summary>
|
|
/// 字典辅助扩展方法.
|
|
/// </summary>
|
|
[SuppressSniffer]
|
|
public static class DictionaryExtensions
|
|
{
|
|
|
|
/// <summary>
|
|
/// 从字典中获取值,不存在则返回字典<typeparamref name="TValue"/>类型的默认值.
|
|
/// </summary>
|
|
/// <typeparam name="TKey">字典键类型.</typeparam>
|
|
/// <typeparam name="TValue">字典值类型.</typeparam>
|
|
/// <param name="dictionary">要操作的字典.</param>
|
|
/// <param name="key">指定键名.</param>
|
|
/// <returns>获取到的值.</returns>
|
|
public static TValue GetOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
|
|
{
|
|
return dictionary.TryGetValue(key, out TValue value) ? value : default(TValue);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 获取指定键的值,不存在则按指定委托添加值.
|
|
/// </summary>
|
|
/// <typeparam name="TKey">字典键类型.</typeparam>
|
|
/// <typeparam name="TValue">字典值类型.</typeparam>
|
|
/// <param name="dictionary">要操作的字典.</param>
|
|
/// <param name="key">指定键名.</param>
|
|
/// <param name="addFunc">添加值的委托.</param>
|
|
/// <returns>获取到的值.</returns>
|
|
public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TValue> addFunc)
|
|
{
|
|
if (dictionary.TryGetValue(key, out TValue value))
|
|
{
|
|
return value;
|
|
}
|
|
|
|
return dictionary[key] = addFunc();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 替换值.
|
|
/// </summary>
|
|
/// <param name="dictionary1"></param>
|
|
/// <param name="dictionary2"></param>
|
|
public static void ReplaceValue(this Dictionary<string, object> dictionary1, Dictionary<string, object> dictionary2)
|
|
{
|
|
foreach (var item in dictionary2.Keys)
|
|
{
|
|
if (dictionary1.ContainsKey(item))
|
|
{
|
|
dictionary1[item] = dictionary2[item];
|
|
}
|
|
}
|
|
}
|
|
|
|
private static Dictionary<string, string[]> dicProperties = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase);
|
|
/// <summary>
|
|
/// 字典转换成指定类型实例
|
|
/// added by ly on 20230524
|
|
/// </summary>
|
|
/// <typeparam name="T">转换的目标类型</typeparam>
|
|
/// <param name="dictionary">被转换的字典</param>
|
|
/// <returns>转换后的目标类型对象实例</returns>
|
|
public static T ToObject<T>(this Dictionary<String, Object> dictionary) where T : class, new()
|
|
{
|
|
var name = typeof(T).Name;
|
|
T instance = new();
|
|
if (!dicProperties.TryGetValue(name, out string[] properies))
|
|
{
|
|
properies = instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).Select(p => p.Name).ToArray();
|
|
dicProperties[name] = properies;
|
|
}
|
|
foreach (var pn in properies)
|
|
{
|
|
if (dictionary.ContainsKey(pn))
|
|
{
|
|
instance.PropertySetValue(pn, dictionary[pn]);
|
|
}
|
|
}
|
|
return instance;
|
|
}
|
|
} |