c# - 将集合 (HashSet) 隐式转换为 IEnumerable<T>

标签 c# .net linq collections casting

我有一个简单的抽象枚举类:

public abstract class Enumeration<T> {

    protected readonly T _value;
    private static readonly HashSet<Enumeration<T>> _values
        = new HastSet<Enumeration<T>>();

    protected Enumeration(T value) {
        _value = value;
        _values.Add(this);
    }

}

现在我想要一个方法来返回 HashSet 中的每个元素,但不返回 HashSet 本身(-> 作为 IEnumerable)。

但这行不通:

public static IEnumerable<T> GetValues() {
     return _values;
}

因为我不能隐式转换 HashSetIEnumerable<T> , 当然。我能想到的唯一方法是遍历 HashSet 并生成每个元素,但我想知道是否有一种方法可以自动执行此操作,例如当您将列表隐式转换为 IEnumerable<T> 时。 .

最佳答案

你可以隐式转换HashSet<T>IEnumerable<T> ,因为 HashSet 和其他通用集合类型一样,实现了 IEnumerable<T> .

但是,由于显而易见的原因,您无法转换 HashSet<U>IEnumerable<T> , 除非 U可转换为 T (在这种情况下,您可以使用隐式协变转换)。

你的 HashSet是(但可能不应该是)Enumeration<T> 的集合, 不是 T .

关于c# - 将集合 (HashSet) 隐式转换为 IEnumerable<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17882115/

相关文章:

c# - 此代码的 LINQ 方法

c# - 使用linq连接2个具有不同结构的表

C# - 通过子类实现的接口(interface)继承和使用时找不到方法的用法

c# - 用 C# 编写文件浏览器的最现代方法是什么

.net - 如何确保无法验证的 .NET 程序集有效?

c# - 这可以改进吗?清除危险的 html 标签

.net - Windows Server 2008 上的最大 tcp/ip 连接数

c# - 如何以编程方式随机生成游戏对象?

c# - 在不使用语句的情况下使用 Entity Framework 的缺点?

c# - LINQ Orderby 降序查询