在C#中,可以使用各种不同的数据结构来存储和操作数据。以下是一些常见数据结构的初始化示例:
1.数组 (Array):
// 声明并初始化整型数组
int[] intArray = new int[] { 1, 2, 3, 4, 5 };// 声明并初始化字符串数组
string[] stringArray = new string[] { "apple", "banana", "orange" };
2.列表 (List):
// 声明并初始化整型列表
List<int> intList = new List<int>() { 1, 2, 3, 4, 5 };// 声明并初始化字符串列表
List<string> stringList = new List<string>() { "apple", "banana", "orange" };
3.字典 (Dictionary):
// 声明并初始化字典,键为字符串,值为整型
Dictionary<string, int> myDictionary = new Dictionary<string, int>()
{{"apple", 1},{"banana", 2},{"orange", 3}
};
4.集合 (Set):
// 声明并初始化集合
HashSet<int> mySet = new HashSet<int>() { 1, 2, 3, 4, 5 };
5.堆栈 (Stack):
// 声明并初始化堆栈
Stack<int> myStack = new Stack<int>();
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
6.队列 (Queue):
// 声明并初始化队列
Queue<string> myQueue = new Queue<string>();
myQueue.Enqueue("apple");
myQueue.Enqueue("banana");
myQueue.Enqueue("orange");