c# - 如何比较两个 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());
}
}
解决方案
我想到了。我创建了一个抽象类,它具有用于实现 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()。希望这对遇到此问题的其他人有所帮助。
推荐阅读
- python - 有没有办法改变图像的中心?旋转图像
- sql - Postgresql:如何获取一个json,其中一列是键,另一列是值?
- node.js - 如何改进返回 5000 条记录的查询?
- reactjs - 将 ReactNode 数组传递给功能组件时出现类型检查错误
- javascript - Laravel 编辑页面在服务器上时不会调用 CSS 和 JS
- python - 根据列表值过滤列结果
- xpath - Xpath - 查找特定元素,打印该节点的所有元素
- excel - 从运行宏中排除工作表
- unit-testing - 如何使用 mocha-junit-reporter 打印失败的测试
- flutter - 将 admob 添加到同一屏幕时,Flutter webview 不起作用