C# 从装箱int到uint的转换生成System.OverflowException
我试图以编程方式将装箱的int转换为uint 我使用的代码是:C# 从装箱int到uint的转换生成System.OverflowException,c#,C#,我试图以编程方式将装箱的int转换为uint 我使用的代码是: Type targetType = methodToInvoke.GetParameters()[index].ParameterType; object operand = currentMethod.Body.Instructions[j - 1].Operand; if (targetType.IsValueType) { parameters[index] = Convert.ChangeType(operand,
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位,为什么会发生这种情况
- 我该怎么做这个转换呢
Convert.ChangeType
只是从IConvertible
接口调用方法,该接口使用值语义
发件人:
Convert.ChangeType方法(对象, (类型)
返回指定类型的对象,其值与指定对象等效
(增加重点)
我该怎么做这个转换呢
听起来你只是想要一个快速的位转换,这可以通过拆开int
并转换到unit
来实现:
unchecked {
parameters[index] = (uint)(int)operand;
}
或者,如果您不喜欢未选中的操作:
parameters[index] = BitConverter.ToUInt32(BitConverter.GetBytes((int)operand), 0)
等等,你是在问为什么不能将负整数转换成无符号整数?想一想。是的,这绝对是我要问的。也许我在Convert.ChangeType中没有抓住要点,但这绝对是可能的。那么,我该怎么做这个转换呢?谢谢你的回复,非常清楚。所以我想没有一个“通用”的方法来做到这一点。我的意思是,在我的代码段操作数和targetType可以是任何合理的类型,这意味着在您的解决方案中,我必须显式地管理“int”情况。不,没有“generic”
BitConverter
,因为进程高度依赖于目标和目标类型。例如,将字节
转换为uint
不同于将长
转换为短
。这是有意义的。谢谢