微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在C#中使用HpecSets进行类型转换

我有两个类,一个派生出另一个.我还有一个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; } }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐