在C#.Net中,我们可以使用sbyte创建一个带符号的字节数组,sbyte用于存储-128到127(带符号的8位整数)范围内的两个值(负值和正值)。
每个元素占用1字节的内存,如果数组大小为10,则将占用10字节的内存。
1)具有初始化的数组声明
Syntax: sbyte[] array_name = { byte1, byte2, byte2, ...};
Example: sbyte[] arr1 = { -128, -100, 0, 100, 127};具有固定数量元素的阵列装饰
Syntax: sbyte[] array_name = new sbyte[value]; Example: sbyte[] arr2 = new sbyte[5];
3)带有用户输入的数组声明
Syntax: sbyte[] array_name = new sbyte[variable]; Example: sbyte[] arr3 = new sbyte[n];
像其他类型的数组一样,我们可以使用其索引访问数组元素,索引以0开头,以n-1结尾。此处,n是数组元素的总数。
示例
考虑给定的示例–在这里,我们使用3种不同的方法声明3个数组,并使用默认值或用户输入来初始化数组。为了打印数组元素,我们使用了foreach循环,我们也可以使用带有循环计数器的for或while循环来访问数组元素。
using System;
using System.Text;
namespace Test
{
class Program
{
static void Main(string[] args)
{
//declaring signed byte[] & initializing it with 5 elements
sbyte[] arr1 = { -128, -100, 0, 100, 127 };
//打印arr1的所有字节
Console.WriteLine("arr1 items...");
foreach (sbyte item in arr1)
{
Console.WriteLine(item);
}
Console.WriteLine(); //打印一行
//声明5个元素的数组
//读取值并分配给数组
sbyte[] arr2 = new sbyte[5];
//从用户那里读取值
for (int loop = 0; loop < 5; loop++)
{
Console.Write("Enter a byte (b/w -128 to 127): ");
arr2[loop] = sbyte.Parse(Console.ReadLine());
}
//打印arr2的所有字节
Console.WriteLine("arr2 items...");
foreach (sbyte item in arr2)
{
Console.WriteLine(item);
}
Console.WriteLine(); //打印一行
//读取“ n”的值并声明“ n”个元素的数组"n" and declare array for "n" elements
//读取值并分配给数组
Console.Write("Enter length of the array: ");
int n = int.Parse(Console.ReadLine());
//为n个元素声明数组
sbyte[] arr3 = new sbyte[n];
//从用户那里读取值
for (int loop = 0; loop < n; loop++)
{
Console.Write("Enter a byte (b/w -128 to 127): ");
arr3[loop] = sbyte.Parse(Console.ReadLine());
}
//打印arr3的所有字节
Console.WriteLine("arr3 items...");
foreach (sbyte item in arr3)
{
Console.WriteLine(item);
}
//按ENTER退出
Console.ReadLine();
}
}
}输出结果
arr1 items... -128 -100 0 100 127 Enter a byte (b/w -128 to 127): 127 Enter a byte (b/w -128 to 127): 100 Enter a byte (b/w -128 to 127): -100 Enter a byte (b/w -128 to 127): 0 Enter a byte (b/w -128 to 127): 20 arr2 items... 127 100 -100 0 20 Enter length of the array: 3 Enter a byte (b/w -128 to 127): -128 Enter a byte (b/w -128 to 127): 0 Enter a byte (b/w -128 to 127): 127 arr3 items... -128 0 127