C#中的GetType()和Typeof()

itemVal = "0"; res = int.TryParse(itemVal, out num); if ((res == true) && (num.GetType() == typeof(byte))) return true; else return false; // goes here when I debugging. 

为什么num.GetType() == typeof(byte)不返回true

因为numint ,而不是byte

GetType()在运行时获取对象的System.Type 。 在这种情况下,它与typeof(int)相同,因为num是一个int

typeof()在编译时获取类型的System.Type对象。

您的评论表明您正在尝试确定该数字是否适合一个字节; 变量的内容不会影响其类型(实际上,它是限制其内容的变量的类型)。

您可以通过这种方式检查数字是否适合一个字节:

 if ((num >= 0) && (num < 256)) { // ... } 

或者这样,使用强制转换:

 if (unchecked((byte)num) == num) { // ... } 

看来您的整个代码示例可以替换为以下内容:

 byte num; return byte.TryParse(itemVal, num); 

只是因为你要比较一个byte和一个int

如果你想知道字节数,试试这个简单的片段:

 int i = 123456; Int64 j = 123456; byte[] bytesi = BitConverter.GetBytes(i); byte[] bytesj = BitConverter.GetBytes(j); Console.WriteLine(bytesi.Length); Console.WriteLine(bytesj.Length); 

输出:

 4 8 

因为和int和一个字节是不同的数据类型。

int(众所周知)是4字节(32位)Int64,或Int16分别是64或16位

一个字节只有8位

如果num是一个int,它将永远不会返回true

如果你想检查这个int值是否适合一个字节,你可以测试以下内容;

 int num = 0; byte b = 0; if (int.TryParse(itemVal, out num) && byte.TryParse(itemVal, b)) { return true; //Could be converted to Int32 and also to Byte }