| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using Quadarax.Foundation.Core.Reflection.Extensions;
- namespace Quadarax.Foundation.Core.Object.Extensions
- {
- public static class ObjectExt
- {
- public static IDictionary<string, object> GetAllPropertyValues(this object obj,string indentPrefix = null)
- {
- var props = new Dictionary<string, object>();
- if (obj == null)
- return props;
- if (string.IsNullOrEmpty(indentPrefix))
- indentPrefix = string.Empty;
- var type = obj.GetType();
- var propList = type.GetAllProperties();
- foreach (var prop in propList)
- {
- var val = prop.GetValue(obj, new object[] { });
- if (val is IEnumerable enumerable && !(val is string))
- {
- var cnt = 0;
- foreach (var item in enumerable)
- {
- var itemProps = item.GetAllPropertyValues(prop.Name + $"[{cnt}].");
- foreach (var ip in itemProps)
- props.Add(ip.Key, ip.Value);
- cnt++;
- }
- }
- else
- props.Add(indentPrefix + prop.Name, val);
- }
-
- return props;
- }
-
- public static void SetAllPropertyValues(this object obj,IDictionary<string, object> values,string indentPrefix = null, bool silent = false)
- {
- if (obj == null)
- return;
- if (values == null || values.Count == 0)
- return;
- if (string.IsNullOrEmpty(indentPrefix))
- indentPrefix = string.Empty;
- var type = obj.GetType();
- var propList = type.GetAllProperties();
- foreach (var val in values)
- {
- var propName = val.Key;
- var prop = propList.FirstOrDefault(x => x.Name == val.Key);
- if (prop == null)
- if (!silent)
- throw new InvalidOperationException(
- $"Cannot locate property '{val.Key}' in class '{obj.GetType().Name}'.");
- prop.SetValue(obj,val);
- }
- }
-
- }
- }
|