在 C# 中操作 HashSet<string> 类型的白名单非常简单,以下是具体操作方法:
HashSet<string> whiteList = new HashSet<string>
{
    "192.168.1.100",
    "10.0.0.5"
};
一、添加白名单地址
1、逐个添加
whiteList.Add("192.168.1.101");  // 添加单个地址
whiteList.Add("10.0.0.6");
2. 批量添加
// 方法1:使用 Add 方法遍历添加
string[] newIps = { "172.16.0.1", "172.16.0.2" };
foreach (string ip in newIps)
{
    whiteList.Add(ip);
}
// 方法2:使用 UnionWith 合并集合
HashSet<string> additionalIps = new HashSet<string> { "203.0.113.5", "198.51.100.10" };
whiteList.UnionWith(additionalIps);  // 自动去重合并
二、移除白名单地址
1、移除单个地址
bool removed = whiteList.Remove("10.0.0.5");  // 返回 true 表示成功
if (removed) 
{
    Console.WriteLine("已移除指定IP");
}
2. 批量移除
// 方法1:遍历移除
string[] removeIps = { "192.168.1.100", "203.0.113.5" };
foreach (string ip in removeIps)
{
    whiteList.Remove(ip);
}
// 方法2:使用 ExceptWith 差集操作
HashSet<string> ipsToRemove = new HashSet<string> { "198.51.100.10", "172.16.0.1" };
whiteList.ExceptWith(ipsToRemove);  // 从白名单中排除指定集合
三、清空白名单
whiteList.Clear();  // 移除所有元素
Console.WriteLine($"清空后白名单数量:{whiteList.Count}");  // 输出 0
四、完整操作示例
using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        // 初始化白名单
        HashSet<string> whiteList = new HashSet<string>
        {
            "192.168.1.100",
            "10.0.0.5"
        };
        // 添加操作
        whiteList.Add("172.16.0.3");
        whiteList.UnionWith(new[] { "203.0.113.4", "203.0.113.5" });
        // 移除操作
        whiteList.Remove("10.0.0.5");
        whiteList.ExceptWith(new[] { "203.0.113.4" });
        // 输出当前白名单
        Console.WriteLine("当前白名单:");
        foreach (string ip in whiteList)
        {
            Console.WriteLine(ip);
        }
        
        //判断是否有内容
        if (whiteList.Count > 0)
        {
            Console.WriteLine("whiteList 中有内容。");
        }
        else
        {
            Console.WriteLine("whiteList 是空的。");
        }
        // 清空操作
        whiteList.Clear();
    }
}
关键注意事项
- 唯一性保证
 - HashSet会自动去重,重复添加相同地址不会有副作用:
 
whiteList.Add("192.168.1.100");  // 已存在时自动忽略
- 大小写敏感
 地址字符串区分大小写,建议统一使用小写:
 
whiteList.Add("192.168.1.100".ToLower());  // 推荐统一格式
- IP格式验证
 建议添加前验证地址格式有效性:
 
if (IPAddress.TryParse("192.168.1.100", out _))
{
    whiteList.Add("192.168.1.100");
}
- 性能优势
 - HashSet的添加(- Add)和查找(- Contains)操作时间复杂度为 O(1),适合高频操作。
 
通过上述方法,您可以灵活地动态管理白名单地址。如果需要持久化存储,建议将白名单保存到配置文件或数据库中,并在程序启动时加载到 HashSet 中。
该文章在 2025/3/14 22:27:28 编辑过