public static void GenerateMatchedObject(TParent parent, TChild child) { var childProperties = child.GetType().GetProperties(); foreach (var childProperty in childProperties) { var attributeForProperty = childProperty.GetCustomAttributes(typeof(MatchParentAttribute), true); var isOfTypeMatchParentAttribute = false; MatchParentAttribute currentAttribute = null; foreach (var attribute in attributeForProperty) { if (attribute.GetType() == typeof(MatchParentAttribute)) { isOfTypeMatchParentAttribute = true; currentAttribute = (MatchParentAttribute)attribute; break; } } if (isOfTypeMatchParentAttribute) { var parentProperties = parent.GetType().GetProperties(); object parentPropertyValue = null; foreach (var parentProperty in parentProperties) { if (parentProperty.Name == currentAttribute.ParentPropertyName) { if (parentProperty.PropertyType == childProperty.PropertyType) { parentPropertyValue = parentProperty.GetValue(parent); } } } childProperty.SetValue(child, parentPropertyValue); } } }
public static void MatchPropertiesFrom(this object self, object parent) { var childProperties = self.GetType().GetProperties(); foreach (var childProperty in childProperties) { var attributesForProperty = childProperty.GetCustomAttributes(typeof(MatchParentAttribute), true); var isOfTypeMatchParentAttributes = false; MatchParentAttribute currrentAttributes = null; foreach (var attribute in attributesForProperty) { if (attribute.GetType() == typeof(MatchParentAttribute)) { isOfTypeMatchParentAttributes = true; currrentAttributes = (MatchParentAttribute)attribute; break; } } if (isOfTypeMatchParentAttributes) { var parentProperties = parent.GetType().GetProperties(); object parentPropertyValue = null; foreach (var parenProperty in parentProperties) { if (parenProperty.Name == currrentAttributes.ParentPropertyName) { if (parenProperty.PropertyType == childProperty.PropertyType) { parentPropertyValue = parenProperty.GetValue(parent); } } } childProperty.SetValue(self, parentPropertyValue); } } }