문제

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