The following code leads to an InvalidCastException.

  object x = (short) 1;
  int y = (int) x;

I know that I could cast x first to a short and then to an int, although that is not an option, as the type of the boxed value is not known (but it is definetly smaller than an int).

How can I work around the exception when unboxing to a type, that is larger than the boxed type?

Edit: I solved my problem by using the dynamic type (with all the performance implications)

有帮助吗?

解决方案

You can only unbox an object to its exact type.

Instead, you should call Convert.ToInt32(), which will work with any numeric type.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top