首页 > 解决方案 > 如何比较两个 Object 类型的变量?

问题描述

我面临的问题是我想比较两个 CustomerEntity 类型的对象。有时,要比较的两个对象都在 EntityID、EntityType 和 EntityName 上匹配,因此我还需要一种比较 EntityObject 的方法。

public class CustomerEntity 
{
  public string EntityID { get; set; }
  public string EntityName { get; set; }
  public string EntityType { get; set; }
  public object EntityObject { get; set; }
}

EntityObject 的值可以是几种不同类型的对象之一,具体取决于 EntityType 的值。EntityObject 可以是的所有类型都实现了 IComparable,但基本的 Object 类没有,那么我该如何比较它们呢?

以下是 EntityObject 可能是的类的示例:

    public class EquipmentEntity : IEquatable<EquipmentEntity>, IComparable<EquipmentEntity>
    {
        public string Manufacturer { get; set; }
        public string Model { get; set; }
        public int ModelYear { get; set; }

        public override bool Equals(object obj)
        {
            return EqualityTester(this, obj as EquipmentEntity);
        }

        public bool Equals(EquipmentEntity other)
        {
            return EqualityTester(this, other);
        }

        public override int GetHashCode()
        {
            return (Manufacturer + Model + ModelYear.ToString()).GetHashCode();
        }

        private static bool EqualityTester(EquipmentEntity a, EquipmentEntity b)
        {
            if (a.Manufacturer.ToLower().Equals(b.Manufacturer.ToLower()) == false ) { return false; }
            if (a.Model.ToLower().Equals(b.Model.ToLower()) == false ) { return false; }
            if (a.ModelYear.Equals(b.ModelYear) == false ) { return false; }
            return true;
        }

        public int CompareTo(object obj)
        {
            return ComparisonTester(this, obj as EquipmentEntity);
        }

        public int CompareTo(EquipmentEntity other)
        {
            return ComparisonTester(this, other);
        }

        private static int ComparisonTester(EquipmentEntity a, EquipmentEntity b)
        {
            if (a is null && b != null) { return -1; }
            if (a != null && b is null) { return 1; }
            if (a is null && b is null) { return 0; }
            return (a.Manufacturer + a.Model + a.ModelYear.ToString()).CompareTo(b.Manufacturer + b.Model + b.ModelYear.ToString());
        }
    }

标签: c#icomparable

解决方案


我想到了。我创建了一个抽象类,它具有用于实现 IComparable (CompareTo) 和 IEquitable (Equals, GetHashCode) 方法的抽象方法。

public abstract class EntityWrapper : IComparable<EntityWrapper>, IEquatable<EntityWrapper>
    {
        public abstract override bool Equals(Object obj);
        public abstract bool Equals(EntityWrapper other);
        public abstract override int GetHashCode();
        public abstract int CompareTo(Object obj);
        public abstract int CompareTo(EntityWrapper other);
    }

实际的实体对象类提供了它们自己的这些方法的实现,这些方法由通用 Linq 方法调用,例如 .Equals() 和 .Sort()。希望这对遇到此问题的其他人有所帮助。


推荐阅读