GetType() and Typeof() in C#

后端 未结 5 1425
粉色の甜心
粉色の甜心 2021-01-21 20:17
itemVal = \"0\";

res = int.TryParse(itemVal, out num);

if ((res == true) && (num.GetType() == typeof(byte)))  
    return true;
else
   return false;  // goes          


        
相关标签:
5条回答
  • 2021-01-21 20:21

    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
    }
    
    0 讨论(0)
  • 2021-01-21 20:32

    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);
    
    0 讨论(0)
  • 2021-01-21 20:33

    If num is an int it will never return true

    0 讨论(0)
  • 2021-01-21 20:39

    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
    
    0 讨论(0)
  • 2021-01-21 20:41

    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

    0 讨论(0)
提交回复
热议问题