开发者

Comparing two integral variables cast to object?

开发者 https://www.devze.com 2023-02-14 13:32 出处:网络
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.

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); 
0

精彩评论

暂无评论...
验证码 换一张
取 消