Boxed Value Type comparisons

前端 未结 2 661
走了就别回头了
走了就别回头了 2021-02-13 12:50

What i\'m trying to achieve here is a straight value comparison of boxed primitive types.

((object)12).Equals((object)12); // Type match will result in a value c         


        
2条回答
  •  情书的邮戳
    2021-02-13 13:14

    Look into using IComparable instead of manual if's - http://msdn.microsoft.com/en-us/library/system.icomparable.compareto.aspx.

    If you need something similar in future consider swith on types of one operand first and implementing "operation handler" class for each of the types with method to handle the operation like IntOpHandler.PerformOp(int left, object right).

    You can also often decrease number of types you need to deal with by merging multiple types togeter first (i.e. byte, short, ushort, int, uint, long - cast to long first, then perform operations on long).

提交回复
热议问题