取消装箱uint/int而不知道盒子里面有什么

Joh*_*lph 7 c# boxing coercion

我有一个object o已知的盒装intuint:

object o = int.MinValue
object o = (uint)int.MinValue // same bytes as above
Run Code Online (Sandbox Code Playgroud)

我不知道盒子里有什么,我关心的是那里有4个字节,我想强迫一个int或者uint.unchecked当我有值(而不是框)时,这在上下文中工作正常:

unchecked
{
    int a = (int)0x80000000u; // will be int.MinValue, the literal is a uint
    uint b = (uint)int.MinValue;
}
Run Code Online (Sandbox Code Playgroud)

注意:默认情况下,C#中的所有内容都是未选中的,因此我们只需要处理文字并且编译器想知道我们是否真的想要用脚射击自己.

现在的问题是我不知道盒子里面是什么(除了它是4个字节),但是当我尝试将unbox打包到错误的类型时,运行时会这样做InvalidCastException.我知道这是合理的运行时行为,但在这种情况下我知道我在做什么并想要一个"未经检查的unbox".这样的事情存在吗?

我知道我可以catch重试,所以这不算作答案.

Qua*_*ter 4

如果可能的话,您可以使用Convert.ToInt32将任何对象转换为 int,尽管它也会进行转换或解析,因此可能比您想要的要慢。

如果你知道它是 int 或 uint,你可以这样做:

int x = (o is int) ? (int)o : (int)(uint)o;
Run Code Online (Sandbox Code Playgroud)