GetType()和Typeof()在C#中 [英] GetType() and Typeof() in C#

查看:131
本文介绍了GetType()和Typeof()在C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  itemVal =0; 

res = int.TryParse(itemVal,out num); ((res == true)&&(num.GetType()== typeof(byte)))
return true;

if
else
返回false; //我在调试的时候会去这里。

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

解决方案

c $ c> num 是 int ,而不是字节



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



typeof()获取 System.Type



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

你可以检查数字是否会如果((num> = 0)&&(num< 256))符合一个字节:

  ){
// ...
}

或者这样,使用演员:
$ b $ pre $ if(unchecked((byte)num)== num){
// ...
}

然而,您的整个代码示例似乎可以替换为:

 字节数; 
返回byte.TryParse(itemVal,num);


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 ?

解决方案

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);

这篇关于GetType()和Typeof()在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆