加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 17:16:53 所属栏目:百科 来源:网络整理
导读:我有两个类,一个派生出另一个.我还有一个HashSet字段,它存储了一堆Derived类.问题是Derived类只在内部使用,我有一个属性需要返回一个基类的HashSet.我知道List有ConvertAll方法,HashSet有类似的东西吗? public class Base{}public class MyClass{ private c
我有两个类,一个派生出另一个.我还有一个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; } }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读