You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多类型对象集合相等比较方法实现咨询(含代码)

Completing the Multi-Type Object Collection Equality Method

Let's refine your method to properly compare all elements in the collection, handling nulls, type checks, and full equality across every item. Here's the completed implementation with explanations:

Final Implementation

public static bool Compare(bool compareTypes = false, params object[] values)
{
    // Handle null or empty input (no objects to compare)
    if (values == null || values.Length == 0)
        return false;
    
    // Single element is trivially equal to itself
    if (values.Length == 1)
        return true;
    
    object reference = values[0];
    
    if (!compareTypes)
    {
        // Compare all elements to the reference using Object.Equals (handles nulls and overridden equality)
        for (int i = 1; i < values.Length; i++)
        {
            if (!object.Equals(reference, values[i]))
                return false;
        }
        return true;
    }
    else
    {
        // Enforce type matching first, then value equality
        
        // If reference is null, all elements must be null (null has no type)
        if (reference == null)
        {
            foreach (var item in values.Skip(1))
            {
                if (item != null)
                    return false;
            }
            return true;
        }
        
        Type referenceType = reference.GetType();
        
        foreach (var item in values.Skip(1))
        {
            // Non-null reference means no null items are allowed
            if (item == null)
                return false;
            
            // Check for exact type match (derived types don't count)
            if (item.GetType() != referenceType)
                return false;
            
            // Verify value equality
            if (!object.Equals(reference, item))
                return false;
        }
        
        return true;
    }
}

Key Improvements & Explanations

  • Edge Case Handling:

    • Null or empty arrays return false (since there's no set of objects to consider "all the same").
    • Single-element arrays return true—there's nothing to compare against, so it's trivially equal.
  • Non-Type Comparison:

    • Uses object.Equals instead of == to properly handle:
      • Null values (object.Equals(null, null) returns true).
      • Custom types where Equals(object) is overridden for value equality (instead of reference equality from ==).
    • Iterates through all elements, not just the first two, to ensure every item matches the reference.
  • Type-Enforced Comparison:

    • If the reference element is null, all other elements must also be null (since null has no type, any non-null item would have a mismatched type).
    • For non-null references:
      • No null elements are allowed (they can't match the reference's type).
      • Checks for exact type matches (derived types won't pass—e.g., int vs long or BaseClass vs DerivedClass).
      • Verifies value equality after confirming type matches.

Example Usage

// Non-type comparison
Compare(false, 5, 5, 5); // True
Compare(false, "apple", "apple", "banana"); // False
Compare(false, null, null); // True

// Type-enforced comparison
Compare(true, 5, 5, 5); // True
Compare(true, 5, (double)5); // False (int vs double)
Compare(true, null, "test"); // False (null vs string)
Compare(true, new List<int>(), new List<int>()); // False (reference equality for List)

Note: For custom reference types to work correctly with value equality, you'll need to override Equals(object) and GetHashCode() in your class.

内容的提问来源于stack exchange,提问作者Héctor M.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:58:48