If you don't know the type at compile time, then you can't unbox because you have nowhere to put it - all you can do is store it in an object
, which is: boxed.
The same also applies to reference-types like string
: you can't cast it to the right type if you don't know the type at compile time: you have nowhere to put it.
You can special-case a few types, for example:
if(obj is int) {
int i = (int)obj;
...
} ...
Another trick that is sometimes (not often) helpful is to switch into generics; then instead of talking in terms of object
you are talking in terms of T
. This has... limited use though. The easiest way to do that is via dynamic, for example:
dynamic obj = ...
Foo(obj);
...
Foo<T>(T val) { ... code with T ... }
you can also add special cases to that appreach:
Foo(string val) { ... code with string ...}
Foo(int val) { ... code with int ...}
However, frankly I suggest it may be better to look hard at what you are trying to do.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…