简体   繁体   中英

Find difference between two objects in C#

I'm looking for a way to find the difference between the values of properties between two objects of the same type.

I've been working from the example in this stack overflow question:

Finding property differences between two C# objects

This is what I have so far:

public static string Compaire<T>(T initial, T final)
{
    Type currentType = initial.GetType();
    PropertyInfo[] props = currentType.GetProperties();
    StringBuilder sb = new StringBuilder();

    foreach (var prop in props)
    {

        Type equatable = prop.PropertyType.GetInterface("System.IEquatable");

        if (equatable != null)
        {
            var i = prop.GetValue(initial);
            var f = prop.GetValue(final);

            if (i!= null && f != null && !i.Equals(f))
            {
                sb.Append(String.Format(_"{0}.{1} has changed from {2} to {3}. ", currentType.BaseType.Name, prop.Name, i, f));
            }
        }

    }
    return sb.ToString();
}

This is working for most cases however, nullable properties (like Nullable int for example) are not getting compared because (I think) they are not being unboxed and nullable isn't implemented with IEquatable.

Using this method of reflection, is it possible to compare nullables while still avoiding entities that have been disposed (eg "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection")?

You could use object.Equals(i,f) and omit the check for IEquatable. If it is neccessary but you would like to include nullables you could include them the following way:

        if (prop.PropertyType.IsGenericType)
        {
            if (prop.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                Type typeParameter = prop.PropertyType.GetGenericArguments()[0];

                var i = prop.GetValue(initial);
                var f = prop.GetValue(final);  
                if(object.Equals(i,f))
                {
                    //...
                }
            }
        }

So you check explicitly for Nullables. The first line checks if the type is generic (true for Nullable List etc.) The second gets the underlying generic type (Nullable<>, List<>) and compares it with the Nullable<> type. The third line gets the first (and in case of Nullable<> only) parameter, just for the case you are interested in what type the Nullable is. So you will get int for Nullable. It is not needed in the code I written, but perhaps you are interested in it. Then the values of both properties are read and compared.

也许这个项目可以满足您的需求: CompareNetObjects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM