Created
July 28, 2022 14:15
-
-
Save BrunoDSouza/a9b36db6f7c35e012e8e37d4ca0003de to your computer and use it in GitHub Desktop.
Extensões para Objetos em C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class ObjectExtensions | |
{ | |
public static bool HasValueProperty(this object obj, string propertyName) | |
{ | |
if (!obj.ExistsProperty(propertyName)) | |
return false; | |
var type = obj.GetType(); | |
var properties = type.GetProperties(); | |
var allProperties = AllProperties(properties); | |
var prop = allProperties.FirstOrDefault(x => x.Property.Name == propertyName); | |
if (prop.Parent != null) | |
{ | |
var valueParent = prop.Parent.GetValue(obj); | |
return valueParent != null && prop.Property.GetValue(valueParent) != null; | |
} | |
return prop.Property.GetValue(obj) != null; | |
} | |
public static bool ExistsProperty(this object obj, string propertyName) | |
{ | |
var type = obj.GetType(); | |
var properties = type.GetProperties(); | |
return AllProperties(properties).Select(x => x.Property.Name).Contains(propertyName); | |
} | |
private static IEnumerable<(PropertyInfo Property, PropertyInfo? Parent)> AllProperties(IEnumerable<PropertyInfo> properties, PropertyInfo parent = null) | |
{ | |
return properties.Aggregate(new List<(PropertyInfo property, PropertyInfo? parent)>(), (list, property) => | |
{ | |
if (isSimpleProperty(property)) | |
{ | |
list.Add((property, parent: parent ?? default(PropertyInfo))); | |
return list; | |
} | |
list.Add((property, parent: default(PropertyInfo))); | |
var props = AllProperties(property.PropertyType.GetProperties(), property); | |
list.AddRange(props); | |
return list; | |
}); | |
} | |
private static bool isSimpleProperty(PropertyInfo prop) | |
=> prop.PropertyType.IsPrimitive || | |
prop.PropertyType.IsEnum || | |
(prop.PropertyType.Namespace?.Equals("System") ?? false); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment