C#中的GetType()和Typeof()

Nan*_* HE 2 c# function gettype c#-2.0

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.
Run Code Online (Sandbox Code Playgroud)

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

Cam*_*ron 5

因为numint,不是byte.

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

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

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

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

if ((num >= 0) && (num < 256)) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

或者这样,使用演员表:

if (unchecked((byte)num) == num) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

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

byte num;
return byte.TryParse(itemVal, num);
Run Code Online (Sandbox Code Playgroud)