public static IDictionary <string, object> ObjectToDictionaryCached(object obj, MemberTypes memberTypes = MemberTypes.Property, ObjectToDictionaryFlags flags = ObjectToDictionaryFlags.None) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if ((memberTypes & ~(MemberTypes.Field | MemberTypes.Property)) != 0) { throw new ArgumentException(Resources.FieldOrPropertyAllowedOnly, nameof(memberTypes)); } Type type = obj.GetType(); #pragma warning disable IDE0018 // Inline variable declaration MemberDescriptor[] memberDescriptors; #pragma warning restore IDE0018 // Inline variable declaration #if !NETSTANDARD1_0 LazyInitializer.EnsureInitialized(ref s_memberDescriptorCache, () => new System.Collections.Concurrent.ConcurrentDictionary <Type, MemberDescriptor[]>()); #else LazyInitializer.EnsureInitialized(ref s_memberDescriptorCache, () => new Dictionary <Type, MemberDescriptor[]>()); lock (s_memberDescriptorCache) #endif if (!s_memberDescriptorCache.TryGetValue(type, out memberDescriptors)) { memberDescriptors = GetObjectToDictionaryMembers(type).Select(MemberDescriptor.Create).ToArray(); #if !NETSTANDARD1_0 s_memberDescriptorCache.TryAdd(type, memberDescriptors); #else s_memberDescriptorCache.Add(type, memberDescriptors); #endif } var excludeReadOnly = (flags & ObjectToDictionaryFlags.ExcludeReadOnlyProperties) != 0; var dictionary = new Dictionary <string, object>((flags & ObjectToDictionaryFlags.IgnoreCase) == 0 ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase); MemberDescriptor memberDescriptor; for (int i = 0, n = memberDescriptors.Length; i < n; i++) { if (((memberDescriptor = memberDescriptors[i]).Member.MemberType() & memberTypes) != 0 && (!excludeReadOnly || !memberDescriptor.IsReadOnly)) { dictionary.Add(memberDescriptor.Member.Name, memberDescriptor.ValueAccessor(obj)); } } return(dictionary); }
public static IDictionary <string, object> ObjectToDictionary(object obj, MemberTypes memberTypes = MemberTypes.Property, ObjectToDictionaryFlags flags = ObjectToDictionaryFlags.None) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if ((memberTypes & ~(MemberTypes.Field | MemberTypes.Property)) != 0) { throw new ArgumentException(Resources.FieldOrPropertyAllowedOnly, nameof(memberTypes)); } var excludeReadOnly = (flags & ObjectToDictionaryFlags.ExcludeReadOnlyProperties) != 0; var dictionary = new Dictionary <string, object>((flags & ObjectToDictionaryFlags.IgnoreCase) == 0 ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase); foreach (MemberInfo member in GetObjectToDictionaryMembers(obj.GetType())) { if ((member.MemberType() & memberTypes) != 0) { object value; if (member is PropertyInfo property) { if (excludeReadOnly && IsPropertyReadOnly(property)) { continue; } value = property.GetValue(obj, null); } else { value = ((FieldInfo)member).GetValue(obj); } dictionary.Add(member.Name, value); } } return(dictionary); }