java 集合 emptySet() 的 C# 等价物是什么

What is the C# equivalent for java Collections emptySet()

在我的代码中,我想 return 一个空集。

在java中我可以使用标准的静态emptySet()方法Collectionsclass。

C# 是否存在等效的 method/constant?

===== 部分代码:

    private static HashSet<string> CreateSetWithProcessedIds()
    {
        if (!File.Exists(processedIdsFilePath))
        {
            // return empty set here
        }


    }

编辑 2:

我想 return 一个空的且不可变的集合,当没有保存的数据存在时。如果保存的数据存在,我想创建一个 HashSet 并将其 return 到调用者进程。调用者进程将以只读模式使用此集合。

如果您发现它比标准实例化更干净,您可以使用类似的东西

HashSet<int> hs = Enumerable.Empty<int>().ToHashSet();

由于集合是只读的,return 类型应更改为 IReadOnlySet<T>IReadOnlySet 接口提供设置功能,无需任何修改方法。返回 IReadOnlySet 意味着如果有人试图修改代码甚至无法编译。

private static IReadOnlySet<string> CreateSetWithProcessedIds()
{
    if (!File.Exists(processedIdsFilePath))
    {
        return Immutable.ImmutableHashSet<string>.Empty;
    }

    var mySet=new HashSet<string>();
    ...
    return mySet;

}

ImmutableHashSet.Empty 字段包含一个实现 IReadOnlySet<T> 的静态不可变哈希集实例,因此可以在需要 IReadOnlySet<T> 时使用它。

Immutable 类似于“普通”数组、字典和集合,但是任何修改操作 return 一个 new 集合和修改后的数据修改原件。这意味着它们对于读取和写入都是线程安全的,并且任何更改仅对修改代码可见。