GetType() and Typeof() in C#

百般思念 提交于 2019-12-09 03:43:30

问题


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.

Why num.GetType() == typeof(byte) does not return true ?


回答1:


Because num is an int, not a byte.

GetType() gets the System.Type of the object at runtime. In this case, it's the same as typeof(int), since num is an int.

typeof() gets the System.Type object of a type at compile-time.

Your comment indicates you're trying to determine if the number fits into a byte or not; the contents of the variable do not affect its type (actually, it's the type of the variable that restricts what its contents can be).

You can check if the number would fit into a byte this way:

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

Or this way, using a cast:

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

It seems your entire code sample could be replaced by the following, however:

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



回答2:


Simply because you are comparing a byte with an int

If you want to know number of bytes try this simple snippet:

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

Output:

4
8



回答3:


because and int and a byte are different data types.

an int (as it is commonly known) is 4 bytes (32 bits) an Int64, or Int16 are 64 or 16 bits respectively

a byte is only 8 bits




回答4:


If num is an int it will never return true




回答5:


If you wanna check if this int value would fit a byte, you might test the following;

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
}


来源:https://stackoverflow.com/questions/5386434/gettype-and-typeof-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!