我在这里想要实现的是盒装原始类型的直接值比较。
((object)12).Equals((object)12); // Type match will result in a value comparison,
((object)12).Equals((object)12d); // but a type mismatch will not. (false)
object.Equals((object)12,(object)12d); // Same here. (false)
我明白“为什么”。我只是没有看到“如何”。
这些类型在运行时之前是未知的,它们可以是来自数据源的任何原始类型。这包括字符串、日期时间、布尔值等。我已经走了一条丑陋的路线,编写了一个可以解决两种类型的扩展方法,然后在进行“==”比较之前进行强制转换:(为了完整起见,我包括了每个原始类型,加上我感兴趣的那些)
public static bool ValueEquals(this object thisObj, object compare)
{
if (thisObj is int)
{
int obj = (int)thisObj;
if (compare is int)
return (obj == (int)compare);
if (compare is uint)
return (obj == (uint)compare);
if (compare is decimal)
return (obj == (decimal)compare);
if (compare is float)
return (obj == (float)compare);
<... and so on for each primitive type ...>
}
if (thisObj is uint)
{
uint obj = (uint)thisObj;
if (compare is int)
return (obj == (int)compare);
if (compare is uint)
return (obj == (uint)compare);
<... Again for each primitive type ...>
}
if (thisObj is decimal)
{
decimal obj = (decimal)thisObj;
if (compare is int)
return (obj == (int)compare);
<... Etc, etc ...>
结果方法结果是 300 多行,这很好(但很可怕),但现在我需要做的不仅仅是“==”。我需要 >、<、<=、>=、!=。
反射中有什么可以用于盒装值类型比较的吗?
有什么吗?