首页主机资讯c# add方法怎样使用

c# add方法怎样使用

时间2024-10-18 16:44:06发布访客分类主机资讯浏览957
导读:在C#中,Add方法通常用于向集合(如List、Dictionary等)中添加元素。以下是使用Add方法的一些示例: 向List中添加元素: using System; using System.Collections.Generic;...

在C#中,Add方法通常用于向集合(如List、Dictionary等)中添加元素。以下是使用Add方法的一些示例:

  1. 向List中添加元素:
using System;
    
using System.Collections.Generic;


class Program
{

    static void Main()
    {
    
        List<
    int>
     numbers = new List<
    int>
    ();
    

        // 使用Add方法向List中添加元素
        numbers.Add(1);
    
        numbers.Add(2);
    
        numbers.Add(3);


        // 输出List中的元素
        foreach (int number in numbers)
        {
    
            Console.WriteLine(number);

        }

    }

}
    
  1. 向Dictionary中添加元素:
using System;
    
using System.Collections.Generic;


class Program
{

    static void Main()
    {
    
        Dictionary<
    string, int>
     ages = new Dictionary<
    string, int>
    ();
    

        // 使用Add方法向Dictionary中添加元素
        ages.Add("Alice", 30);
    
        ages.Add("Bob", 25);
    
        ages.Add("Charlie", 35);
    

        // 输出Dictionary中的元素
        foreach (KeyValuePair<
    string, int>
 entry in ages)
        {

            Console.WriteLine($"Name: {
entry.Key}
, Age: {
entry.Value}
    ");

        }

    }

}
    

在这些示例中,我们首先导入了必要的命名空间(SystemSystem.Collections.Generic),然后创建了List和Dictionary对象。接下来,我们使用Add方法向这些对象中添加元素。最后,我们使用循环遍历并输出集合中的元素。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: c# add方法怎样使用
本文地址: https://pptw.com/jishu/703627.html
c# add方法性能如何评估 c#快速排序法能在线学习吗

游客 回复需填写必要信息