比较两个整数对象是否相等,而与类型无关 [英] Compare two integer objects for equality regardless of type

查看:170
本文介绍了比较两个整数对象是否相等,而与类型无关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何才能将两个装箱的整数(可以有符号或无符号)相互比较以确保相等.

I'm wondering how you could compare two boxed integers (either can be signed or unsigned) to each other for equality.

例如,看一下这种情况:

For instance, take a look at this scenario:

// case #1
object int1 = (int)50505;
object int2 = (int)50505;
bool success12 = int1.Equals(int2); // this is true. (pass)

// case #2
int int3 = (int)50505;
ushort int4 = (ushort)50505;
bool success34 = int3.Equals(int4); // this is also true. (pass)

// case #3
object int5 = (int)50505;
object int6 = (ushort)50505;
bool success56 = int5.Equals(int6); // this is false. (fail)

我很困惑如何以这种方式可靠地比较盒装整数类型.我要等到运行时才能知道它们是什么,我也不能将它们都强制转换为long,因为其中一个可能是ulong.我也不能只将它们都转换为ulong,因为一个可能是负数.

I'm stumped on how to reliably compare boxed integer types this way. I won't know what they are until runtime, and I can't just cast them both to long, because one could be a ulong. I also can't just convert them both to ulong because one could be negative.

我能想到的最好的主意是只是反复试验,直到找到通用类型或排除它们不相等为止,这不是理想的解决方案.

The best idea I could come up with is to just trial-and-error-cast until I can find a common type or can rule out that they're not equal, which isn't an ideal solution.

推荐答案

在情况2中,您实际上最终调用了int.Equals(int),因为ushort可隐式转换为int.此重载解析是在编译时执行的.在情况3中不可用,因为编译器仅将int5int6的类型识别为object,因此它将调用object.Equals(object) ...,并且很自然地object.Equals将返回false(如果类型)这两个对象是不同的.

In case 2, you actually end up calling int.Equals(int), because ushort is implicitly convertible to int. This overload resolution is performed at compile-time. It's not available in case 3 because the compiler only knows the type of int5 and int6 as object, so it calls object.Equals(object)... and it's natural that object.Equals will return false if the types of the two objects are different.

可以在执行时使用动态类型执行相同类型的重载解析-但是,如果尝试执行类似以下操作,您仍然会遇到问题:

You could use dynamic typing to perform the same sort of overload resolution at execution time - but you'd still have a problem if you tried something like:

dynamic x = 10;
dynamic y = (long) 10;
Console.WriteLine(x.Equals(y)); // False

这里没有可以处理long的重载,因此它将调用普通的object.Equals.

Here there's no overload that will handle long, so it will call the normal object.Equals.

一种选择是将值转换为decimal:

One option is to convert the values to decimal:

object x = (int) 10;
object y = (long) 10;
decimal xd = Convert.ToDecimal(x);
decimal yd = Convert.ToDecimal(y);
Console.WriteLine(xd == yd);

这还将处理将ulonglong进行比较.

This will handle comparing ulong with long as well.

我选择decimal是因为它可以精确表示每种原始整数类型的每个值.

I've chosen decimal as it can exactly represent every value of every primitive integer type.

这篇关于比较两个整数对象是否相等,而与类型无关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆