SequenceEqual()与自定义类和浮点值

时间:2016-06-13 21:23:38

标签: c# floating-point equality

我有一个方法返回List<GradingResult>

   public class GradingResult
    {
        public float Grade { get; set; }
        public int Score { get; set; }
    }

该列表的浮点格式值为6到1:

6, 5.9, 5.8, ... 1.2, 1.1,1

现在在我的单元测试中,我有一个带测试数据的测试GradingResult列表:

      new List<GradingResult> {

                 new GradingResult{ Score = 0,Grade = 6.0f},
                 new GradingResult{ Score = 1,Grade = 5.8f},
                 new GradingResult{ Score = 2,Grade = 5.7f},
                 new GradingResult{ Score = 3,Grade = 5.5f},
                 new GradingResult{ Score = 4,Grade = 5.4f},
                 new GradingResult{ Score = 5,Grade = 5.2f},
                 new GradingResult{ Score = 6,Grade = 5.1f},
                 new GradingResult{ Score = 7,Grade = 4.9f},
                 new GradingResult{ Score = 8,Grade = 4.7f},
                 new GradingResult{ Score = 9,Grade = 4.6f },
                 new GradingResult{ Score = 10, Grade = 4.4f },
                 new GradingResult{ Score = 11, Grade = 4.3f},
                 new GradingResult{ Score = 12, Grade = 4.1f},
                 new GradingResult{ Score = 13, Grade = 4.0f},
                 new GradingResult{ Score = 14, Grade = 3.8f},
                 new GradingResult{ Score = 15, Grade = 3.7f},
                 new GradingResult{ Score = 16, Grade = 3.5f},
                 new GradingResult{ Score = 17, Grade = 3.3f},
                 new GradingResult{ Score = 18, Grade = 3.2f},
                 new GradingResult{ Score = 19, Grade = 3.0f},
                 new GradingResult{ Score = 20, Grade = 2.9f},
                 new GradingResult{ Score = 21, Grade = 2.7f},
                 new GradingResult{ Score = 22, Grade = 2.6f},
                 new GradingResult{ Score = 23, Grade = 2.4f},
                 new GradingResult{ Score = 24, Grade = 2.2f},
                 new GradingResult{ Score = 25, Grade = 2.1f},
                 new GradingResult{ Score = 26, Grade = 1.9f},
                 new GradingResult{ Score = 27, Grade = 1.8f},
                 new GradingResult{ Score = 28, Grade = 1.6f},
                 new GradingResult{ Score = 29, Grade = 1.5f},
                 new GradingResult{ Score = 30, Grade = 1.3f},
                 new GradingResult{ Score = 31, Grade = 1.2f},
                 new GradingResult {Score = 32, Grade = 1.0f },
        }, "nextparameter"


            );

现在我将计算出的gradingResult与测试gradingResult进行比较:

Assert.IsTrue(gradingResults.SequenceEqual(testGradingResults));

测试不是绿色,尽管由于此处的定义,两个结果列表应该相同:

https://msdn.microsoft.com/en-us/library/bb348567(v=vs.100).aspx

我的猜测是整个等级如评分结果6,5,4,3,2,1和测试评分结果6.0,5.0,4.0,3.0,2.0,1.0是测试失败的原因。

请有人请说明这种情况吗?

为什么测试失败?我的样本非常类似于Pets样本!

1 个答案:

答案 0 :(得分:1)

您需要覆盖EqualsGetHashCode方法。否则,它使用引用相等性,并且由于列表中的对象不是相同的实例,Equals返回false。