1. 两个数组互相拷贝
方法1:使用循环
int[] sourceArray = { 1, 2, 3, 4, 5 };
int[] destinationArray = new int[sourceArray.Length];
for (int i = 0; i < sourceArray.Length; i++)
{
destinationArray[i] = sourceArray[i];
}
方法2:使用Array.Copy方法
int[] sourceArray = { 1, 2, 3, 4, 5 };
int[] destinationArray = new int[sourceArray.Length];
Array.Copy(sourceArray, destinationArray, sourceArray.Length);
2. 向char[] array中拷贝字符串
方法1:使用char数组的构造函数
string str = "Hello, World!";
char[] charArray = new char[str.Length];
str.CopyTo(0, charArray, 0, str.Length);
方法2:使用Array.Copy方法
string str = "Hello, World!";
char[] charArray = new char[str.Length];
Array.Copy(str.ToCharArray(), 0, charArray, 0, str.Length);
方法3:使用循环
string str = "Hello, World!";
char[] charArray = new char[str.Length];
for (int i = 0; i < str.Length; i++)
{
charArray[i] = str[i];
}
方法4:使用string.ToCharArray方法
string str = "Hello, World!";
char[] charArray = str.ToCharArray();
3. 使用string 数组
//声明未初始化的字符串数组
string[] stringArray;
// 声明并初始化字符串数组
string[] stringArray = new string[3];
stringArray[0] = "Hello";
stringArray[1] = "World";
stringArray[2] = "C#";
// 使用数组初始化器声明并初始化字符串数组
string[] stringArray = { "Hello", "World", "C#" };
// 访问字符串数组的元素
// 访问第一个元素
Console.WriteLine(stringArray[0]); // 输出: Hello
// 访问最后一个元素
Console.WriteLine(stringArray[2]); // 输出: C#
4. 操作list<byte>,删除制定长度的元素
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个包含一些字节的List<byte>
List<byte> byteList = new List<byte> { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06 };
// 假设我们想要删除从索引2开始的3个元素
int index = 2; // 起始索引
int count = 3; // 要删除的元素数量
// 检查索引和数量是否有效
if (index >= 0 && index < byteList.Count && (index + count) <= byteList.Count)
{
// 删除指定范围的元素
byteList.RemoveRange(index, count);
}
// 输出结果
foreach (byte b in byteList)
{
Console.WriteLine(b);
}
}
}
5. C#中将int 转换为byte[]
using System;
class Program
{
static void Main()
{
int intValue = 123456789; // 示例整数
byte[] byteArray = BitConverter.GetBytes(intValue);
// 输出字节数组的内容
foreach (byte b in byteArray)
{
Console.Write(b + " ");
}
}
}