Comparing two integral variables cast to object?
Say that I have an class that has a property named value of type object. That property will get assigned integral whole types, short, uint, int32, int64 etc.
Is there some performant way to do comparisons on that property, like obj1.Value > obj2.Value?
Naturally this will generate an error, I guess I could do a method with logic like
if (value1 is Int64 && value2 is Int32)
{
return (Int64) value1 > (Int32) value2;
}
else if (value1 is Int32 && value2 is Int64)
{
return (Int32) value1 > (Int64) value2;
}
etc etc for all combinations, but it seems rather cludgy :) I'd rather not use reflection nor dy开发者_如何转开发namic for performance reasons. Basically what I want is polymorphic operands
You could convert each value to a double
.
return Convert.ToDouble(value1) > Convert.ToDouble(value2);
You could do something like this
return ( Convert.ToInt64(value1) > Convert.ToInt64(value1) );
which is equivalent to
return ((IConvertible)value1).ToInt64(null) > ((IConvertible)value2).ToInt64(null);
精彩评论