using NCC.Dependency;
using NCC.Extensions;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text.Json;
namespace NCC.ClayObject.Extensions
{
///
/// ExpandoObject 对象拓展
///
[SuppressSniffer]
public static class ExpandoObjectExtensions
{
///
/// 将对象转 ExpandoObject 类型
///
///
///
public static ExpandoObject ToExpandoObject(this object value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value is Clay clay && clay.IsObject)
{
dynamic clayExpando = new ExpandoObject();
var dic = (IDictionary)clayExpando;
foreach (KeyValuePair item in (dynamic)clay)
{
dic.Add(item.Key, item.Value is Clay v ? v.ToExpandoObject() : item.Value);
}
return clayExpando;
}
if (value is JsonElement jsonElement && jsonElement.ValueKind == JsonValueKind.Object)
{
dynamic clayExpando = new ExpandoObject();
var dic = (IDictionary)clayExpando;
var objDic = jsonElement.ToObject() as IDictionary;
foreach (var item in objDic)
{
dic.Add(item);
}
return clayExpando;
}
if (value is not ExpandoObject expando)
{
expando = new ExpandoObject();
var dict = (IDictionary)expando;
var dictionary = value.ToDictionary();
foreach (var kvp in dictionary)
{
dict.Add(kvp);
}
}
return expando;
}
///
/// 移除 ExpandoObject 对象属性
///
///
///
public static void RemoveProperty(this ExpandoObject expandoObject, string propertyName)
{
if (expandoObject == null)
throw new ArgumentNullException(nameof(expandoObject));
if (propertyName == null)
throw new ArgumentNullException(nameof(propertyName));
((IDictionary)expandoObject).Remove(propertyName);
}
///
/// 判断 ExpandoObject 是否为空
///
///
///
public static bool Empty(this ExpandoObject expandoObject)
{
return !((IDictionary)expandoObject).Any();
}
///
/// 判断 ExpandoObject 是否拥有某属性
///
///
///
///
public static bool HasProperty(this ExpandoObject expandoObject, string propertyName)
{
if (expandoObject == null)
throw new ArgumentNullException(nameof(expandoObject));
if (propertyName == null)
throw new ArgumentNullException(nameof(propertyName));
return ((IDictionary)expandoObject).ContainsKey(propertyName);
}
///
/// 实现 ExpandoObject 浅拷贝
///
///
///
public static ExpandoObject ShallowCopy(this ExpandoObject expandoObject)
{
return Copy(expandoObject, false);
}
///
/// 实现 ExpandoObject 深度拷贝
///
///
///
public static ExpandoObject DeepCopy(this ExpandoObject expandoObject)
{
return Copy(expandoObject, true);
}
///
/// 拷贝 ExpandoObject 对象
///
///
///
///
private static ExpandoObject Copy(ExpandoObject original, bool deep)
{
var clone = new ExpandoObject();
var _original = (IDictionary)original;
var _clone = (IDictionary)clone;
foreach (var kvp in _original)
{
_clone.Add(
kvp.Key,
deep && kvp.Value is ExpandoObject eObject ? DeepCopy(eObject) : kvp.Value
);
}
return clone;
}
}
}