相关疑难解决方法(0)

试图将boxed int强制转换为byte

代码说明:

        int i = 5;
        object obj = i;
        byte b = (byte)obj; // X
Run Code Online (Sandbox Code Playgroud)

运行时,会在"X"行生成System.InvalidCastException("指定的强制转换无效").做双重演奏:

        byte b = (byte)(int)obj;
Run Code Online (Sandbox Code Playgroud)

我本以为你应该能够将一个盒装的int(如果它的值在0..255范围内)转换成一个字节.任何人都可以对此有所了解吗?

(这是.net 2.0,如果重要的话).

.net c# casting c#-2.0

7
推荐指数
2
解决办法
2152
查看次数

.Net - 转换或转换盒装字节?,简称?还是int?到int?

如果我有一个object引用a 的引用byte?,short?或者int?有没有办法无条件地将该对象引用转换为int?没有为每个案例编写单独的代码?

例如:

byte? aByte = 42; // .. or aByte = null
object anObject = aByte;
//...
var anInt = (int?)anObject //As expected, doesn't work
Run Code Online (Sandbox Code Playgroud)

.net c# int casting nullable

1
推荐指数
1
解决办法
2172
查看次数

标签 统计

.net ×2

c# ×2

casting ×2

c#-2.0 ×1

int ×1

nullable ×1