mercredi 18 mai 2016

Reflection - Compare properties of subclasses

I have a method who compare (with Reflection) the properties of two objects the same type :

public static void AreEquals(object objectA, object objectB)
{
    if (objectA != null && objectB != null)
    {
        Type objectType;

        objectType = objectA.GetType();

        foreach (PropertyInfo propertyInfo in objectType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.CanRead))
        {
            object valueA = propertyInfo.GetValue(objectA, null);
            object valueB = propertyInfo.GetValue(objectB, null);

            if (typeof(IComparable).IsAssignableFrom(propertyInfo.PropertyType) || propertyInfo.PropertyType.IsPrimitive || propertyInfo.PropertyType.IsValueType)
            {
                if (!AreValuesEqual(valueA, valueB))
                    Console.WriteLine(propertyInfo.Name + " not equal");
            }
            else
                Console.WriteLine(propertyInfo.Name + " not equal");
        }
    }
}

private static bool AreValuesEqual(object valueA, object valueB)
{
    bool result;

    IComparable selfValueComparer = valueA as IComparable;

    if (valueA == null && valueB != null || valueA != null && valueB == null)
        result = false;

    else if (selfValueComparer != null && selfValueComparer.CompareTo(valueB) != 0)
        result = false;

    else if (!object.Equals(valueA, valueB))
        result = false;

    else
        result = true;

    return result;
}

But this method does not compare the properties of subclasses.

How to change this method to enter and compare in the properties of subclasses?

Thank you





Aucun commentaire:

Enregistrer un commentaire