我有一个简单的抽象枚举类:
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
.
关于c# - 将集合 (HashSet) 隐式转换为 IEnumerable<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17882115/