using System.Reflection;
using System.Text.RegularExpressions;
namespace Alchemy.Core.Extensions
{
public static class ObjectExtension
{
///
/// 判断对象是否为null
///
///
///
public static bool IsNull(this object? obj)
{
return obj is null;
}
public static bool IsNotNull(this object? obj)
{
return !obj.IsNull();
}
public static bool SetPropValue(this object? obj, string strPropName, object value)
{
bool result = false;
if (obj.IsNull())
return result;
Type type = obj.GetType();
PropertyInfo propertyInfo = type.GetProperty(strPropName);
if (propertyInfo != null && propertyInfo.CanWrite)
{
propertyInfo.SetValue(obj, value, null);
result = true;
}
return result;
}
///
/// 下划线转驼峰的转换
///
///
///
///
public static Dictionary ToDictionary(this object? obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
var dictionary = new Dictionary();
foreach (var property in obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
var key = ToCamelCase(property.Name);
var value = property.GetValue(obj, null);
dictionary[key] = value;
}
return dictionary;
}
private static string ToCamelCase(string input)
{
return Regex.Replace(input, "([a-z])_([a-z])", m => m.Groups[1].Value + m.Groups[2].Value.ToUpperInvariant());
}
}
}