📜  C#中的字节关键字

📅  最后修改于: 2021-05-29 20:37:09             🧑  作者: Mango

关键字是用于某些内部过程或表示某些预定义动作的语言中的单词。 byte是用于声明变量的关键字,该变量可以存储从0到255的无符号值范围。它是System.Byte的别名。

byte关键字在内存中占用1个字节(8位)。

句法:

byte variable_name = value;

例子:

Input: 250

Output: number: 250
        Size of a byte variable: 1

Input: 150

Output: Type of num1: System.Byte
        num1: 150
        Size of a byte variable: 1

范例1:

// C# program to show the usage of byte keyword
using System;
using System.Text;
  
class GFG {
  
    static void Main(string[] args)
    {
        // byte variable declaration
        byte num = 255;
  
        // to print value
        Console.WriteLine("num: " + num);
  
        // to print size of a byte
        Console.WriteLine("Size of a byte variable: " + sizeof(byte));
    }
}

输出:

num: 255
Size of a byte variable: 1

范例2:

// C# program to show the usage of byte keyword
using System;
using System.Text;
  
class GFG {
  
    static void Main(string[] args)
    {
        // byte variable declaration
        byte num1 = 261;
  
        // to print value
        Console.WriteLine("num1: " + num1);
  
        // to print size of a byte
        Console.WriteLine("Size of a byte variable: " + sizeof(byte));
    }
}

错误:输入的数字超出(0-255)范围时。

Constant value `261' cannot be converted to a `byte'

范例3:

// C# program to show the usage of byte keyword
using System;
using System.Text;
  
namespace geeks {
  
class GFG {
    static void Main(string[] args)
    {
        // byte variable declaration
        byte num1 = 150;
  
        // to print type of variable
        Console.WriteLine("Type of num1: " + num1.GetType());
  
        // to print value
        Console.WriteLine("num1: " + num1);
  
        // to print size of a byte
        Console.WriteLine("Size of a byte variable: " + sizeof(byte));
  
        // hit ENTER to exit
        Console.ReadLine();
    }
}
}

输出:

Type of num1: System.Byte
num1: 150
Size of a byte variable: 1