我有两个类,一个派生出另一个.我还有一个HashSet字段,它存储了一堆Derived类.问题是Derived类只在内部使用,我有一个属性需要返回一个基类的HashSet.我知道List有ConvertAll方法,HashSet有类似的东西吗?
public class Base
{
}
public class MyClass
{
private class Derived : Base
{
}
private HashSet<Derived> mList;
public HashSet<Base> GetList { get { /* Convert mList to HashSet<Base> */ } }
}
最佳答案 您无法转换HashSet< Derived>到HashSet< Base>没有铸造每个项目.
要解释为什么这是不可能的,请看下面的代码示例:
HashSet<Derived> mySet = ...;
HashSet<Base> x = (HashSet<Base>)mySet; // imagine this were possible
x.Add(new Base()); // legal code, but cannot work, since x is really a HashSet<Derived>
但是,由于IEnumerable接口是covariant,因此应该可以:
HashSet<Derived> mySet = ...;
IEnumerable<Base> x = mySet; // works in C# 4
// no problem here, since no items can be added to an IEnumerable
因此,您可以更改方法声明:
public IEnumerable<Base> GetList { get { return mList; } }