using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 创建一个 HashSet 实例
HashSet<int> hashSet = new HashSet<int>();
// 添加元素到 HashSet
hashSet.Add(1);
hashSet.Add(2);
hashSet.Add(3);
// 尝试添加重复元素,不会成功
bool result = hashSet.Add(2); // result 为 false
// 检查 HashSet 是否包含某个元素
bool contains = hashSet.Contains(2); // contains 为 true
// 遍历 HashSet 中的所有元素
foreach (int num in hashSet)
{
Console.WriteLine(num);
}
// 移除某个元素
hashSet.Remove(1);
// 获取 HashSet 的元素数量
int count = hashSet.Count; // count 为 2
}
}
HashSet<T>
是 C# 中的一个集合类,它存储唯一的元素,并且不保证元素的顺序。Add
方法用于向 HashSet
中添加元素。如果尝试添加已存在的元素,则返回 false
。Contains
方法用于检查 HashSet
是否包含指定的元素。Remove
方法用于从 HashSet
中移除指定的元素。Count
属性返回 HashSet
中的元素数量。foreach
循环可以遍历 HashSet
中的所有元素。希望这段代码和解释对你有帮助!
上一篇:c# 线程
下一篇:c#随机数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站