比较“相似性”两个 .net 对象值
我有一个通用的 C# 类比较器例程,它从对象读取值,然后使用反射一一比较它们的属性。
var value1 = property.GetValue(object1, null);
var value2 = property.GetValue(object2, null);
if (!value1.Equals(value2))
{ ......
问题是我的一些浮点/双精度值存在差异,这些差异微不足道,我想忽略。对浮点数/双精度数(以及可能的整数)实施特定测试(根据提供的有效位数比较值)的最佳方法是什么?
I have a generic C# class comparer routine which reads values from objects and then compares their properties one by one using reflection.
var value1 = property.GetValue(object1, null);
var value2 = property.GetValue(object2, null);
if (!value1.Equals(value2))
{ ......
Thing is I'm getting differences in some of my float/double values that are insignificant and I want to ignore. What's the best way of implementing a specific test for floats/doubles (and potentially ints) that compares values based on a provided number of significant digits?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看一下
EqualityComparer
类。恕我直言,您应该依赖相关类型的 Equals 方法,而不是按照您描述的方式比较对象。
也就是说,类的作者应该通过重写
Equals
方法(甚至可能实现IEquality
接口)来定义该类的 2 个实例何时相等。Take a look at the
EqualityComparer<T>
class.Instead of comparing objects in the way you describe, you should rely on the Equals method of the type in question, imho.
That is, the author of the class should define when 2 instances of that class are equal, by overriding the
Equals
method (and perhaps even implementing theIEquality
interface).