vendredi 20 juillet 2018

C# Find properties shared by two types of the same hierarchy

I need to copy the value of properties from one class to another that are descendants of the same base type. Source and target object may be on different levels of the same inheritance branch, meaning one is derived from the other, or be descendant of different branches, meaning they share a common base type.

      A
  B1      B2
C1 C2      C3

From the structure above I may want to copy all properties from A to C1, C2 to C3, C3 to B1, etc. Basically any possible combination from the tree. Obviously I can only copy properties present in the source type, that must also be present in the target type.

Iterating the properties of the source type is easy as

var sourceProperties = source.GetType().GetProperties();

However how do I check which property is declared on the target type? Simply checking by name is not enough, as they might have different types. Also in the past I made bad experiences with duplicate properties using new.

Unfortunately C# or .NET has no built-in method to check if a type has a certain PropertyInfo like Type.HasProperty(PropertyInfo). The best I could come up with is to check if the property was declared by a shared base type.

public static void CopyProperties(object source, object target)
{
    var targetType = target.GetType();
    var sharedProperties =source.GetType().GetProperties()
        .Where(p => p.DeclaringType.IsAssignableFrom(targetType));

    foreach (var property in sharedProperties)
    {
        var value = property.GetValue(source);
        if (property.CanWrite)
            property.SetValue(target, value);
    }
}

Question: Is there a better solution?





Aucun commentaire:

Enregistrer un commentaire