GetType() and Typeof() in C#

后端 未结 5 1426
粉色の甜心
粉色の甜心 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条回答
  •  -上瘾入骨i
    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);
    

提交回复
热议问题