Merge branch 'dev' of ssh://git.tuotong-tech.com:9105/tnb/tnb.server into dev
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
using JNPF.DependencyInjection;
|
||||
using System.Reflection;
|
||||
using JNPF.DependencyInjection;
|
||||
|
||||
namespace JNPF.Common.Extension;
|
||||
|
||||
@@ -8,6 +9,7 @@ namespace JNPF.Common.Extension;
|
||||
[SuppressSniffer]
|
||||
public static class DictionaryExtensions
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 从字典中获取值,不存在则返回字典<typeparamref name="TValue"/>类型的默认值.
|
||||
/// </summary>
|
||||
@@ -55,4 +57,31 @@ public static class DictionaryExtensions
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user