পার্থক্য খুঁজতে দুটি বস্তুর বৈশিষ্ট্যের তুলনা করুন?


155

আমার একই ধরণের দুটি বস্তু রয়েছে এবং আমি সেগুলির প্রত্যেকের সর্বজনীন বৈশিষ্ট্যগুলি লুপ করতে এবং কোন বৈশিষ্ট্য মেলে না সে সম্পর্কে ব্যবহারকারীকে সতর্ক করতে চাই।

বস্তুর কী কী বৈশিষ্ট্য রয়েছে তা না জেনে কি এটি করা সম্ভব?



উত্তর:


212

হ্যাঁ, প্রতিচ্ছবি সহ - প্রতিটি সম্পত্তি ধরণের Equalsযথাযথ প্রয়োগগুলি ধরে নেওয়া । একটি বিকল্প ReflectiveEqualsহ'ল কিছু পরিচিত ধরণের ব্যতীত সকলের জন্য পুনরাবৃত্তভাবে ব্যবহার করা তবে এটি জটিল হয়ে ওঠে।

public bool ReflectiveEquals(object first, object second)
{
    if (first == null && second == null)
    {
        return true;
    }
    if (first == null || second == null)
    {
        return false;
    }
    Type firstType = first.GetType();
    if (second.GetType() != firstType)
    {
        return false; // Or throw an exception
    }
    // This will only use public properties. Is that enough?
    foreach (PropertyInfo propertyInfo in firstType.GetProperties())
    {
        if (propertyInfo.CanRead)
        {
            object firstValue = propertyInfo.GetValue(first, null);
            object secondValue = propertyInfo.GetValue(second, null);
            if (!object.Equals(firstValue, secondValue))
            {
                return false;
            }
        }
    }
    return true;
}

এই পদ্ধতির সাথে পুনরাবৃত্তি ব্যবহার করা এবং অবজেক্টের সমস্ত সংগ্রহের তুলনা করা কি সম্ভব হবে? যেমন অবজেক্ট 1 -> তালিকার (বিদ্যালয়ের) -> তালিকা (শ্রেণির) -> তালিকা (শিক্ষার্থীদের)
পিটার পিটলক

@ পিটারপিটলক: আচ্ছা আপনি সম্ভবত সংগ্রহের জন্য বিভিন্ন হ্যান্ডলিং চাইবেন - কেবল তালিকার বৈশিষ্ট্যগুলির তুলনা করা ভাল কাজ করবে না।
জন স্কিটি

2
ধন্যবাদ জন, আমার কাছে একটি মাস্টারঅজেক্ট (এমও) এবং একটি লাইটওয়েটমাস্টারঅজেক্ট (এলডাব্লুএমও) রয়েছে যা কেবল মাস্টারঅবজেক্টের একটি স্ট্রিপ ডাউন সংস্করণ - তবে উভয়েরই সংগ্রহ রয়েছে - আমি পুনরাবৃত্তি সহ প্রদত্ত কোডটি ব্যবহার করতে পারি কিনা তা দেখার চেষ্টা করছি - এলডাব্লুএমও খালি আছে কখন শুরু হবে, কিন্তু এমও এবং এর বৈশিষ্ট্যগুলির প্রতিটি সংকলনের মধ্য দিয়ে যাওয়ার সময় - সংশ্লিষ্ট এলডাব্লুএমওর মান সেট করা আছে - এই প্রয়োগটি সম্ভবত প্রদত্ত কোডটিতে পুনরাবৃত্তি করার অনুমতি দেবে?
পিটার পিটলক

@ পিটারপিটলক: মনে হচ্ছে আপনার এই মুহুর্তে নতুন প্রশ্ন জিজ্ঞাসা করা উচিত, মূলত - যে প্রশ্নের উত্তরটি দেওয়া হয়েছিল তা আপনার প্রয়োজনীয়তার সাথে যথেষ্ট নয় close
জন স্কিটি

42

নিশ্চিত আপনি প্রতিবিম্ব সহ করতে পারেন। প্রদত্ত ধরণের বৈশিষ্ট্য বন্ধ করে দেওয়ার জন্য এখানে কোড।

var info = typeof(SomeType).GetProperties();

আপনি যদি বৈশিষ্ট্যগুলির সাথে তুলনা করছেন সে সম্পর্কে আপনি যদি আরও তথ্য দিতে পারেন তবে আমরা একত্রে একটি বেসিক ডিফিং অ্যালগরিদম্ন পেতে পারি। Intstance জন্য এই কোড নাম পৃথক হবে

public bool AreDifferent(Type t1, Type t2) {
  var list1 = t1.GetProperties().OrderBy(x => x.Name).Select(x => x.Name);
  var list2 = t2.GetProperties().OrderBy(x => x.Name).Select(x => x.Name);
  return list1.SequenceEqual(list2);
}

আমি মনে করি তিনি একই ধরণের দুটি বস্তু বোঝাতে চেয়েছিলেন যেখানে মানগুলি মেলে না।
বিফ্রি

@ জারেড পার: ডিফিং কাজ করে না। প্রপার্টিআইনফো অবজেক্টগুলি অবশ্যই টাইপ না হলে একই রকম হয় না ...
মেহেরদাদ আফশারি

@ মেহেরদাড, আমার নামগুলির জন্য একটি প্রাথমিক উদাহরণ was আমি আরও নির্দিষ্ট করে দেওয়ার আগে আমি ওপিতে অপেক্ষা করছিলাম যে তারা কীসের সন্ধান করছে to
জারেডপাড়

1
@ জারেডপার: আমি বুঝতে পেরেছি, তবে এটি আসলে নামের জন্য কাজ করে না। যদিও এটি ধারণাটি যোগাযোগ করতে পারে, এটি কিছুটা বিভ্রান্তিকর। ক্রমটি যাইহোক সমান হবে না। আমি একটি যোগ করার পরামর্শ দিচ্ছি.Select(...)
মেহরদাদ আফশারি

দুঃখিত, কেবলমাত্র স্পষ্ট করার জন্য আমি বলতে চাইছিলাম যেখানে বৈশিষ্ট্যের মানগুলি আলাদা। ধন্যবাদ
গ্যাভিন

7

আমি জানি এটি সম্ভবত ওভারকিল, তবে এখানে আমার উদ্দেশ্য বিষয়টির ক্লাসটি আমি এই উদ্দেশ্যে ব্যবহার করছি:

/// <summary>
/// Utility class for comparing objects.
/// </summary>
public static class ObjectComparer
{
    /// <summary>
    /// Compares the public properties of any 2 objects and determines if the properties of each
    /// all contain the same value.
    /// <para> 
    /// In cases where object1 and object2 are of different Types (both being derived from Type T) 
    /// we will cast both objects down to the base Type T to ensure the property comparison is only 
    /// completed on COMMON properties.
    /// (ex. Type T is Foo, object1 is GoodFoo and object2 is BadFoo -- both being inherited from Foo --
    /// both objects will be cast to Foo for comparison)
    /// </para>
    /// </summary>
    /// <typeparam name="T">Any class with public properties.</typeparam>
    /// <param name="object1">Object to compare to object2.</param>
    /// <param name="object2">Object to compare to object1.</param>
    /// <param name="propertyInfoList">A List of <see cref="PropertyInfo"/> objects that contain data on the properties
    /// from object1 that are not equal to the corresponding properties of object2.</param>
    /// <returns>A boolean value indicating whether or not the properties of each object match.</returns>
    public static bool GetDifferentProperties<T> ( T object1 , T object2 , out List<PropertyInfo> propertyInfoList )
        where T : class
    {
        return GetDifferentProperties<T>( object1 , object2 , null , out propertyInfoList );
    }

    /// <summary>
    /// Compares the public properties of any 2 objects and determines if the properties of each
    /// all contain the same value.
    /// <para> 
    /// In cases where object1 and object2 are of different Types (both being derived from Type T) 
    /// we will cast both objects down to the base Type T to ensure the property comparison is only 
    /// completed on COMMON properties.
    /// (ex. Type T is Foo, object1 is GoodFoo and object2 is BadFoo -- both being inherited from Foo --
    /// both objects will be cast to Foo for comparison)
    /// </para>
    /// </summary>
    /// <typeparam name="T">Any class with public properties.</typeparam>
    /// <param name="object1">Object to compare to object2.</param>
    /// <param name="object2">Object to compare to object1.</param>
    /// <param name="ignoredProperties">A list of <see cref="PropertyInfo"/> objects
    /// to ignore when completing the comparison.</param>
    /// <param name="propertyInfoList">A List of <see cref="PropertyInfo"/> objects that contain data on the properties
    /// from object1 that are not equal to the corresponding properties of object2.</param>
    /// <returns>A boolean value indicating whether or not the properties of each object match.</returns>
    public static bool GetDifferentProperties<T> ( T object1 , T object2 , List<PropertyInfo> ignoredProperties , out List<PropertyInfo> propertyInfoList )
        where T : class
    {
        propertyInfoList = new List<PropertyInfo>();

        // If either object is null, we can't compare anything
        if ( object1 == null || object2 == null )
        {
            return false;
        }

        Type object1Type = object1.GetType();
        Type object2Type = object2.GetType();

        // In cases where object1 and object2 are of different Types (both being derived from Type T) 
        // we will cast both objects down to the base Type T to ensure the property comparison is only 
        // completed on COMMON properties.
        // (ex. Type T is Foo, object1 is GoodFoo and object2 is BadFoo -- both being inherited from Foo --
        // both objects will be cast to Foo for comparison)
        if ( object1Type != object2Type )
        {
            object1Type = typeof ( T );
            object2Type = typeof ( T );
        }

        // Remove any properties to be ignored
        List<PropertyInfo> comparisonProps =
            RemoveProperties( object1Type.GetProperties() , ignoredProperties );

        foreach ( PropertyInfo object1Prop in comparisonProps )
        {
            Type propertyType = null;
            object object1PropValue = null;
            object object2PropValue = null;

            // Rule out an attempt to check against a property which requires
            // an index, such as one accessed via this[]
            if ( object1Prop.GetIndexParameters().GetLength( 0 ) == 0 )
            {
                // Get the value of each property
                object1PropValue = object1Prop.GetValue( object1 , null );
                object2PropValue = object2Type.GetProperty( object1Prop.Name ).GetValue( object2 , null );

                // As we are comparing 2 objects of the same type we know
                // that they both have the same properties, so grab the
                // first non-null value
                if ( object1PropValue != null )
                    propertyType = object1PropValue.GetType().GetInterface( "IComparable" );

                if ( propertyType == null )
                    if ( object2PropValue != null )
                        propertyType = object2PropValue.GetType().GetInterface( "IComparable" );
            }

            // If both objects have null values or were indexed properties, don't continue
            if ( propertyType != null )
            {
                // If one property value is null and the other is not null, 
                // they aren't equal; this is done here as a native CompareTo
                // won't work with a null value as the target
                if ( object1PropValue == null || object2PropValue == null )
                {
                    propertyInfoList.Add( object1Prop );
                }
                else
                {
                    // Use the native CompareTo method
                    MethodInfo nativeCompare = propertyType.GetMethod( "CompareTo" );

                    // Sanity Check:
                    // If we don't have a native CompareTo OR both values are null, we can't compare;
                    // hence, we can't confirm the values differ... just go to the next property
                    if ( nativeCompare != null )
                    {
                        // Return the native CompareTo result
                        bool equal = ( 0 == (int) ( nativeCompare.Invoke( object1PropValue , new object[] {object2PropValue} ) ) );

                        if ( !equal )
                        {
                            propertyInfoList.Add( object1Prop );
                        }
                    }
                }
            }
        }
        return propertyInfoList.Count == 0;
    }

    /// <summary>
    /// Compares the public properties of any 2 objects and determines if the properties of each
    /// all contain the same value.
    /// <para> 
    /// In cases where object1 and object2 are of different Types (both being derived from Type T) 
    /// we will cast both objects down to the base Type T to ensure the property comparison is only 
    /// completed on COMMON properties.
    /// (ex. Type T is Foo, object1 is GoodFoo and object2 is BadFoo -- both being inherited from Foo --
    /// both objects will be cast to Foo for comparison)
    /// </para>
    /// </summary>
    /// <typeparam name="T">Any class with public properties.</typeparam>
    /// <param name="object1">Object to compare to object2.</param>
    /// <param name="object2">Object to compare to object1.</param>
    /// <returns>A boolean value indicating whether or not the properties of each object match.</returns>
    public static bool HasSamePropertyValues<T> ( T object1 , T object2 )
        where T : class
    {
        return HasSamePropertyValues<T>( object1 , object2 , null );
    }

    /// <summary>
    /// Compares the public properties of any 2 objects and determines if the properties of each
    /// all contain the same value.
    /// <para> 
    /// In cases where object1 and object2 are of different Types (both being derived from Type T) 
    /// we will cast both objects down to the base Type T to ensure the property comparison is only 
    /// completed on COMMON properties.
    /// (ex. Type T is Foo, object1 is GoodFoo and object2 is BadFoo -- both being inherited from Foo --
    /// both objects will be cast to Foo for comparison)
    /// </para>
    /// </summary>
    /// <typeparam name="T">Any class with public properties.</typeparam>
    /// <param name="object1">Object to compare to object2.</param>
    /// <param name="object2">Object to compare to object1.</param>
    /// <param name="ignoredProperties">A list of <see cref="PropertyInfo"/> objects
    /// to ignore when completing the comparison.</param>
    /// <returns>A boolean value indicating whether or not the properties of each object match.</returns>
    public static bool HasSamePropertyValues<T> ( T object1 , T object2 , List<PropertyInfo> ignoredProperties )
        where T : class
    {

        // If either object is null, we can't compare anything
        if ( object1 == null || object2 == null )
        {
            return false;
        }

        Type object1Type = object1.GetType();
        Type object2Type = object2.GetType();

        // In cases where object1 and object2 are of different Types (both being derived from Type T) 
        // we will cast both objects down to the base Type T to ensure the property comparison is only 
        // completed on COMMON properties.
        // (ex. Type T is Foo, object1 is GoodFoo and object2 is BadFoo -- both being inherited from Foo --
        // both objects will be cast to Foo for comparison)
        if ( object1Type != object2Type )
        {
            object1Type = typeof ( T );
            object2Type = typeof ( T );
        }

        // Remove any properties to be ignored
        List<PropertyInfo> comparisonProps =
            RemoveProperties( object1Type.GetProperties() , ignoredProperties );

        foreach ( PropertyInfo object1Prop in comparisonProps )
        {
            Type propertyType = null;
            object object1PropValue = null;
            object object2PropValue = null;

            // Rule out an attempt to check against a property which requires
            // an index, such as one accessed via this[]
            if ( object1Prop.GetIndexParameters().GetLength( 0 ) == 0 )
            {
                // Get the value of each property
                object1PropValue = object1Prop.GetValue( object1 , null );
                object2PropValue = object2Type.GetProperty( object1Prop.Name ).GetValue( object2 , null );

                // As we are comparing 2 objects of the same type we know
                // that they both have the same properties, so grab the
                // first non-null value
                if ( object1PropValue != null )
                    propertyType = object1PropValue.GetType().GetInterface( "IComparable" );

                if ( propertyType == null )
                    if ( object2PropValue != null )
                        propertyType = object2PropValue.GetType().GetInterface( "IComparable" );
            }

            // If both objects have null values or were indexed properties, don't continue
            if ( propertyType != null )
            {
                // If one property value is null and the other is not null, 
                // they aren't equal; this is done here as a native CompareTo
                // won't work with a null value as the target
                if ( object1PropValue == null || object2PropValue == null )
                {
                    return false;
                }

                // Use the native CompareTo method
                MethodInfo nativeCompare = propertyType.GetMethod( "CompareTo" );

                // Sanity Check:
                // If we don't have a native CompareTo OR both values are null, we can't compare;
                // hence, we can't confirm the values differ... just go to the next property
                if ( nativeCompare != null )
                {
                    // Return the native CompareTo result
                    bool equal = ( 0 == (int) ( nativeCompare.Invoke( object1PropValue , new object[] {object2PropValue} ) ) );

                    if ( !equal )
                    {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /// <summary>
    /// Removes any <see cref="PropertyInfo"/> object in the supplied List of 
    /// properties from the supplied Array of properties.
    /// </summary>
    /// <param name="allProperties">Array containing master list of 
    /// <see cref="PropertyInfo"/> objects.</param>
    /// <param name="propertiesToRemove">List of <see cref="PropertyInfo"/> objects to
    /// remove from the supplied array of properties.</param>
    /// <returns>A List of <see cref="PropertyInfo"/> objects.</returns>
    private static List<PropertyInfo> RemoveProperties (
        IEnumerable<PropertyInfo> allProperties , IEnumerable<PropertyInfo> propertiesToRemove )
    {
        List<PropertyInfo> innerPropertyList = new List<PropertyInfo>();

        // Add all properties to a list for easy manipulation
        foreach ( PropertyInfo prop in allProperties )
        {
            innerPropertyList.Add( prop );
        }

        // Sanity check
        if ( propertiesToRemove != null )
        {
            // Iterate through the properties to ignore and remove them from the list of 
            // all properties, if they exist
            foreach ( PropertyInfo ignoredProp in propertiesToRemove )
            {
                if ( innerPropertyList.Contains( ignoredProp ) )
                {
                    innerPropertyList.Remove( ignoredProp );
                }
            }
        }

        return innerPropertyList;
    }
}

আমি এই উত্তরটি অনেক পছন্দ করি তবে ক্লাসগুলির উদাহরণ ব্যবহার দেখে আমি দেখতে চাই। আমি অবশ্যই আমি যে প্রকল্পে কাজ করছি তার জন্য এটি ব্যবহার করব
ইমোজো

7

আসল সমস্যা: দুটি সেটের পার্থক্য কীভাবে পাবেন?

আমি সবচেয়ে দ্রুততম উপায়টি পেয়েছি সেটিংসটি প্রথমে অভিধানগুলিতে রূপান্তর করা, তারপরে আলাদা dif এখানে একটি সাধারণ পদ্ধতি রয়েছে:

static IEnumerable<T> DictionaryDiff<K, T>(Dictionary<K, T> d1, Dictionary<K, T> d2)
{
    return from x in d1 where !d2.ContainsKey(x.Key) select x.Value;
}

তারপরে আপনি এর মতো কিছু করতে পারেন:

static public IEnumerable<PropertyInfo> PropertyDiff(Type t1, Type t2)
{
    var d1 = t1.GetProperties().ToDictionary(x => x.Name);
    var d2 = t2.GetProperties().ToDictionary(x => x.Name);
    return DictionaryDiff(d1, d2);
}

5

হ্যাঁ. প্রতিবিম্ব ব্যবহার করুন । প্রতিচ্ছবি সহ, আপনি যেমন কিছু করতে পারেন:

//given object of some type
object myObjectFromSomewhere;
Type myObjOriginalType = myObjectFromSomewhere.GetType();
PropertyInfo[] myProps = myObjOriginalType.GetProperties();

এবং তারপরে আপনি সমস্ত ধরণের জিনিসগুলির সাথে তুলনা করতে ফলাফল সম্পত্তি classesnfo ক্লাসগুলি ব্যবহার করতে পারেন।


4

LINQ এবং প্রতিবিম্ব ব্যবহার করে একই ধরণের দুটি বস্তুর তুলনা করা। বিশেষ দ্রষ্টব্য! এটি মূলত জন স্কিটির সমাধানটির পুনর্লিখন, তবে আরও কমপ্যাক্ট এবং আধুনিক সিনট্যাক্স সহ। এটি আরও কিছুটা কার্যকর আইএল উত্পন্ন করা উচিত।

এইটার মতো কিছু একটা হচ্ছে:

public bool ReflectiveEquals(LocalHdTicket serverTicket, LocalHdTicket localTicket)
  {
     if (serverTicket == null && localTicket == null) return true;
     if (serverTicket == null || localTicket == null) return false;

     var firstType = serverTicket.GetType();
     // Handle type mismatch anyway you please:
     if(localTicket.GetType() != firstType) throw new Exception("Trying to compare two different object types!");

     return !(from propertyInfo in firstType.GetProperties() 
              where propertyInfo.CanRead 
              let serverValue = propertyInfo.GetValue(serverTicket, null) 
              let localValue = propertyInfo.GetValue(localTicket, null) 
              where !Equals(serverValue, localValue) 
              select serverValue).Any();
  }

2
পুনরাবৃত্তি দরকারী হবে? লাইনটি এর where !Equals(serverValue, localValue)সাথে প্রতিস্থাপন করুনfirstType.IsValueType ? !Equals(serverValue, localValue) : !ReflectiveEquals(serverValue, localValue)
ড্রাজাস

3
আরও আধুনিক হতে পারে তবে আরও কমপ্যাক্ট নয়। আপনি সবেমাত্র পুরো গোছা সাদা জায়গা থেকে মুক্তি পেয়েছেন এবং এটি পড়া আরও কঠিন করে তুলেছেন।
এলিজার স্টেইনবক

এলিজার স্টেইনবক এটিকে খুব কমই মনে হয়। যখন তিনি শ্বেতস্থান থেকে মুক্তি পেয়েছিলেন এবং তিনি এটি পড়া আরও কঠিন করেছেন, তবে তিনি কী করেছিলেন তা ঠিক নয়। সেখানে লিনকিউ বিবৃতিটি @ জন-স্কিটের উত্তরে পূর্বাভাস বিবৃতিটির চেয়ে আলাদাভাবে সংকলন করেছে। আমি জনের উত্তর পছন্দ করি কারণ এটি একটি সহায়তা সাইট, এবং তার ফর্ম্যাটটি আরও স্পষ্ট, তবে আরও উন্নত উত্তরের জন্য, এটিও ভাল।
জিম ইয়ারব্রো 13

4
যদি "আরও আধুনিক" "পড়া আরও শক্ত" এর সাথে সমান হয় তবে আমরা ভুল পথে চলে যাচ্ছি।
bwegs


1

অনেকে যেমন পুনরাবৃত্তির পদ্ধতির কথা উল্লেখ করেছেন, এটি সেই ফাংশন যা আপনি অনুসন্ধানের নাম এবং সম্পত্তিটি দিয়ে শুরু করতে পারেন:

    public static void loopAttributes(PropertyInfo prop, string targetAttribute, object tempObject)
    {
        foreach (PropertyInfo nestedProp in prop.PropertyType.GetProperties())
        {
            if(nestedProp.Name == targetAttribute)
            {
                //found the matching attribute
            }
            loopAttributes(nestedProp, targetAttribute, prop.GetValue(tempObject);
        }
    }

//in the main function
foreach (PropertyInfo prop in rootObject.GetType().GetProperties())
{
    loopAttributes(prop, targetAttribute, rootObject);
}
আমাদের সাইট ব্যবহার করে, আপনি স্বীকার করেছেন যে আপনি আমাদের কুকি নীতি এবং গোপনীয়তা নীতিটি পড়েছেন এবং বুঝতে পেরেছেন ।
Licensed under cc by-sa 3.0 with attribution required.