Skip to main content
 首页 » 编程设计

c#之将集合 (HashSet) 隐式转换为 IEnumerableT>

2024年01月28日25cmt

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

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; 
} 

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

请您参考如下方法:

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

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

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