c# add方法怎样使用
导读:在C#中,Add方法通常用于向集合(如List、Dictionary等)中添加元素。以下是使用Add方法的一些示例: 向List中添加元素: using System; using System.Collections.Generic;...
在C#中,Add
方法通常用于向集合(如List、Dictionary等)中添加元素。以下是使用Add
方法的一些示例:
- 向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);
}
}
}
- 向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}
");
}
}
}
在这些示例中,我们首先导入了必要的命名空间(System
和System.Collections.Generic
),然后创建了List和Dictionary对象。接下来,我们使用Add
方法向这些对象中添加元素。最后,我们使用循环遍历并输出集合中的元素。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: c# add方法怎样使用
本文地址: https://pptw.com/jishu/703627.html