Type t = typeof(int?); //will get this dynamically
object val = 5; //will get this dynamically
object nVal = Convert.ChangeType(val, t);//getting exception here
I am getting InvalidCastException in above code. For above I could simply write int? nVal = val
, but above code is executing dynamically.
I am getting a value(of non nullable type like int, float, etc) wrapped up in an object (here val), and I have to save it to another object by casting it to another type(which can or cannot be nullable version of it). When
Invalid cast from 'System.Int32' to 'System.Nullable`1[[System.Int32,
mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089]]'.
An int
, should be convertible/type-castable to nullable int
, what is the issue here ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…