Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从装箱int到uint的转换生成System.OverflowException_C# - Fatal编程技术网

C# 从装箱int到uint的转换生成System.OverflowException

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,

我试图以编程方式将装箱的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位,为什么会发生这种情况

  • 我该怎么做这个转换呢

如果这两个值的长度为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
不同于将
转换为
。这是有意义的。谢谢