int
当我试图像这样转换它时,我有int变量的值:
820924
它不起作用
这不起作用
(uint)data[structure["MICROSECONDS"].Index]
我收到"指定演员表无效".例外.
数据存储unchecked((uint)data[structure["MICROSECONDS"].Index])但在运行时我应该尝试转换Specified cast is not valid..我几乎可以肯定.我已经打印了对象值object,但是我不知道如何打印对象类型,但它必须是int.
码:
object value = data[structure["MICROSECONDS"].Index];
Console.WriteLine("xx MICROSECONDS type " + value.GetType());
Console.WriteLine("xx casting " + value);
Console.WriteLine("xx cast ok" + (uint)value);
Run Code Online (Sandbox Code Playgroud)
结果:
xx MICROSECONDS type System.Int32
xx casting 820924
Run Code Online (Sandbox Code Playgroud)
Sno*_*ear 40
首先,您应该检查您的价值类型.您可以通过调用obj.GetType()方法(直接在代码中或在立即窗口中)来执行此操作.
如果是,int那么你可以这样做:
uint u = (uint) (int) obj;
Run Code Online (Sandbox Code Playgroud)
请注意,您的投不同,因为它投射到int,然后转换到uint时你想投给uint.int不能投uint,这就是你得到的原因InvalidCastException.int只能转换为uint.令人困惑的是,转换和强制转换运算符在代码中看起来相同:u = (uint) x.
您可以做的更简单的事情是从Convert类中调用特定的方法:
uint u = Convert.ToUInt32(x);
Run Code Online (Sandbox Code Playgroud)
问题是int存储为object. Int派生自 object 但uint不派生 fromint因此您不能将int存储转换为objectto uint。首先你必须将它转换为int然后 touint因为该转换是有效的。自己试试:
object o = 5;//this is constant that represents int, constant for uint would be 5u
uint i = (uint)o;//throws exception
Run Code Online (Sandbox Code Playgroud)
但这有效:
object o = 5;
int i = (int)o;
uint j = (uint)i;
Run Code Online (Sandbox Code Playgroud)
或者
object o = 5;
uint i = (uint)(int)o; //No matter how this looks awkward
Run Code Online (Sandbox Code Playgroud)