比较数值类型时类型未知 [英] Compare numeric types when types are unknown

查看:99
本文介绍了比较数值类型时类型未知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我想要比较两个值:

I have two values that I want to compare:

var value1 = someProperty.GetValue(x);
var value2 = someOtherProperty.GetValue(y);

if (value1 == value2)
{
   // do something
}

其中, someProperty someOtherProperty 的PropertyInfo 的对象。换句话说,我通过反射得到的值。

where someProperty and someOtherProperty are PropertyInfo objects. In other words, I'm getting the values by reflection.

现在的问题是,如果值1 结束是一个 INT 与值 4 值2 最终被一个字节值为 4 ,我希望能够告诉那些是相同的。有一个不考虑其类型来比较两个数值的方法?最好是将仍然允许是,比方说,两个字符串(所以我真的不能投值2 比较 INT 因为它可能会证明,这是一个字符串)。

The problem is if value1 ends up being an int with the value 4, and value2 ends up being a byte with value 4, I'd like to be able to tell those are the same. Is there a method to compare two numeric values without regard to their type? Preferably one that would still allow be to, say, compare two strings (so I can't really cast value2 to int because it might turn out that it's a string).

推荐答案

一种选择是使用动态。这将使编译器生成动态调用网站,并要求DLR踢来比较在运行时的对象。

One option is to use dynamic. This will make compiler to emit dynamic call site and asks the DLR to kick in to compare the objects at runtime.

object obj1 = (int)4;//Default is int, but added to make intent clear
object obj2 = (byte)4;
Console.WriteLine(obj1 == obj2);
Console.WriteLine((dynamic)obj1 == (dynamic)obj2);



打印

Prints

False
True

这篇关于比较数值类型时类型未知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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