12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- using System.Reflection;
- using System.Text.RegularExpressions;
- namespace Alchemy.Core.Extensions
- {
- public static class ObjectExtension
- {
- /// <summary>
- /// 判断对象是否为null
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// 下划线转驼峰的转换
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- /// <exception cref="ArgumentNullException"></exception>
- public static Dictionary<string, object> ToDictionary(this object? obj)
- {
- if (obj == null)
- throw new ArgumentNullException(nameof(obj));
- var dictionary = new Dictionary<string, object>();
- 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());
- }
- }
- }
|