我正在尝试以编程方式将盒装的int转换为uint。
我正在使用的代码是:
Type targetType = methodToInvoke.GetParameters()[index].ParameterType;
object operand = currentMethod.Body.Instructions[j - 1].Operand;
if (targetType.IsValueType)
{
parameters[index] = Convert.ChangeType(operand, targetType);
}
VS告诉我targetType的类型为:
{Name = "UInt32" FullName = "System.UInt32"}
相反,操作数的类型为:
object {int}
当操作数的值为-1549600314时,ChangeType抛出System.OverflowException。
为什么会发生这种情况,前提是这两个值是32位长?
我该如何进行此转换?
答案 0 :(得分:1)
为什么会发生这种情况,前提是这两个值是32位长?
因为Convert.ChangeType
只调用IConvertible
接口中使用 value 语义的方法。
来自MSDN:
Convert.ChangeType方法(对象,类型)
返回指定类型的对象,其值等效于指定的对象。
(强调补充)
我该如何进行此转换?
听起来你只想要一个快速按位转换,只需将int
拆箱并转换为unit
即可完成:
unchecked {
parameters[index] = (uint)(int)operand;
}
或者如果你不喜欢未经检查的操作:
parameters[index] = BitConverter.ToUInt32(BitConverter.GetBytes((int)operand), 0)