C# 数据结构初始化长度

在C#中,各个数据结构的初始化长度是动态的,下面是一个例子,展示了如何初始化各个数据结构并演示它们的长度:

复制代码
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // 初始化数组
        int[] intArray = new int[] { 1, 2, 3, 4, 5 };
        Console.WriteLine($"数组长度: {intArray.Length}");

        // 初始化列表
        List<int> intList = new List<int>() { 1, 2, 3, 4, 5 };
        Console.WriteLine($"列表长度: {intList.Count}");

        // 初始化字典
        Dictionary<string, int> myDictionary = new Dictionary<string, int>()
        {
            {"apple", 1},
            {"banana", 2},
            {"orange", 3}
        };
        Console.WriteLine($"字典长度: {myDictionary.Count}");

        // 初始化集合
        HashSet<int> mySet = new HashSet<int>() { 1, 2, 3, 4, 5 };
        Console.WriteLine($"集合长度: {mySet.Count}");

        // 初始化堆栈
        Stack<int> myStack = new Stack<int>();
        myStack.Push(1);
        myStack.Push(2);
        myStack.Push(3);
        Console.WriteLine($"堆栈长度: {myStack.Count}");

        // 初始化队列
        Queue<string> myQueue = new Queue<string>();
        myQueue.Enqueue("apple");
        myQueue.Enqueue("banana");
        myQueue.Enqueue("orange");
        Console.WriteLine($"队列长度: {myQueue.Count}");
    }
}

这个示例演示了如何初始化各个数据结构,并且打印出它们的长度。在这个示例中,长度是在初始化后动态确定的,而不需要事先指定固定的长度。

相关推荐
要做朋鱼燕2 分钟前
【数据结构】用堆解决TOPK问题
数据结构·算法
忒可君5 分钟前
C# winform FTP功能
开发语言·windows·c#
十五年专注C++开发1 小时前
CMake进阶: CMake Modules---简化CMake配置的利器
linux·c++·windows·cmake·自动化构建
degree5201 小时前
全平台轻量浏览器推荐|支持Win/macOS/Linux,极速加载+隐私保护+扩展插件,告别广告与数据追踪!
windows·macos·电脑
秋难降1 小时前
LRU缓存算法(最近最少使用算法)——工业界缓存淘汰策略的 “默认选择”
数据结构·python·算法
时光追逐者2 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 50 期(2025年8.11-8.17)
c#·.net·.netcore·.net core
一个会的不多的人2 小时前
C# NX二次开发:操作按钮控件Button和标签控件Label详解
开发语言·c#
咕白m6253 小时前
C# 实现 PDF 转图片 - 分辨率设置、图片格式选择
后端·c#
Jayyih3 小时前
嵌入式系统学习Day19(数据结构)
数据结构·学习
DdduZe4 小时前
8.19作业
数据结构·算法