我想创建具有 5 个属性的对象,每个属性都有 2 个属性。之后,我比较对象是否相同,它们将被归为同一类别。
这是代码:
物品.cs
public class Item
{
public Item()
{
}
public SortProperty SortPropA { get; set; }
public SortProperty SortPropB { get; set; }
public SortProperty SortPropC { get; set; }
public SortProperty SortPropD { get; set; }
public SortProperty SortPropE { get; set; }
public string Name { get; set; }
public string Desc { get; set; }
}
排序属性.cs
public class SortProperty : IEquatable<SortProperty>
{
public string PartName { get; set; }
public string GroupabilityID { get; set; }
public SortProperty()
{
}
public override int GetHashCode()
{
int hash = 19;
hash = hash * 31 + (GroupabilityID == null ? 0 : GroupabilityID.GetHashCode());
hash = hash * 31 + (PartName == null ? 0 : PartName.GetHashCode());
return hash;
}
public bool Equals(SortProperty obj)
{
return (obj == null) ?
false : (GroupabilityID == obj.GroupabilityID) || (PartName == obj.PartName);
}
public override bool Equals(Object obj)
{
SortProperty itemobj = obj as SortProperty;
return itemobj == null ? false : Equals(itemobj);
}
}
Program.cs(测试编码的主类)
class Program
{
static void Main(string[] args)
{
Item objA = new Item();
Item objB = new Item();
// ------ Object A
objA.Name = "Card1";
objA.Desc = "Product Test A";
//Property A
objA.SortPropA = new SortProperty();
objA.SortPropA.PartName = "Plastic A";
objA.SortPropA.GroupabilityID = "A1";
//Property B
objA.SortPropB = new SortProperty();
objA.SortPropB.PartName = "Color Green";
objA.SortPropB.GroupabilityID = "B2";
//Property C
objA.SortPropC = new SortProperty();
objA.SortPropC.PartName = "Visa";
objA.SortPropC.GroupabilityID = "C1";
// ------ Object B
objB.Name = "Card2";
objB.Desc = "Product Test B";
//Property A
objB.SortPropA = new SortProperty();
objB.SortPropA.PartName = "Plastic B";
objB.SortPropA.GroupabilityID = "A2";
//Property B
objB.SortPropB = new SortProperty();
objB.SortPropB.PartName = "Color Lime";
objB.SortPropB.GroupabilityID = "B1";
//Property C
objB.SortPropC = new SortProperty();
objB.SortPropC.PartName = "Visa";
objB.SortPropC.GroupabilityID = "C1";
bool isEqual = objA.Equals(objB);
if (isEqual == true)
Console.WriteLine("Is same");
else
Console.WriteLine("Is different");
Console.ReadKey();
}
}
结果应该返回,因为和(SortPropc)true
之间有相同的属性,但它返回。objA
objB
false
我相信我错过了一些逻辑部分,我已经坐在椅子上 4 个小时但无法修复它。任何人都可以解决它吗?