Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C中的GetType()和Typeof()#_C#_Function_C# 2.0_Gettype - Fatal编程技术网

C# C中的GetType()和Typeof()#

C# C中的GetType()和Typeof()#,c#,function,c#-2.0,gettype,C#,Function,C# 2.0,Gettype,为什么num.GetType()==typeof(byte)不返回true?因为num是一个int,而不是字节 GetType()获取运行时对象的System.Type。在本例中,它与typeof(int)相同,因为num是int typeof()获取编译时类型的System.Type对象 您的注释表示您正在尝试确定数字是否适合一个字节;变量的内容不影响它的类型(实际上,正是变量的类型限制了它的内容) 您可以通过以下方式检查数字是否适合一个字节: itemVal = "0"; res = in

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

因为
num
是一个
int
,而不是
字节

GetType()
获取运行时对象的
System.Type
。在本例中,它与
typeof(int)
相同,因为
num
int

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

您的注释表示您正在尝试确定数字是否适合一个字节;变量的内容不影响它的类型(实际上,正是变量的类型限制了它的内容)

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

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.
但是,您的整个代码示例似乎可以替换为以下内容:

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

只是因为您正在比较
字节
整数

如果您想知道字节数,请尝试以下简单代码段:

byte num;
return byte.TryParse(itemVal, num);
输出:

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

因为和int和字节是不同的数据类型

一个int(众所周知)是4个字节(32位),一个Int64或Int16分别是64或16位


一个字节只有8位

如果num是一个int,它将永远不会返回true

如果要检查此int值是否适合一个字节,可以测试以下内容:

4
8

它是一个整数而不是一个字节?为什么它会返回true?是的,它是一个int,但我需要判断int是否是一个字节。我还实现了一些代码,比如
typeof(ushort)
,typeof(ulong)。我使用
typeof(byte)
来定义
(num>=0)和(num
isByte=res&0xff==res
EDIT:如果未签名,则需要检查符号位+低位。在已检查的构建中,该转换将向下转换为一个字节。是的,这就是我的意思。这是一个构建选项,高级按钮。我相信这就是他的意思。在已检查的构建中,编译器将看到int被向下转换为一个字节,而re可能会溢出,因此它会引发异常。将其包装在
unchecked
语句中,就像您所做的那样,将阻止转换检查。
4
8
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
}