开发者

Typecasting HashSets in C#

开发者 https://www.devze.com 2023-03-06 22:19 出处:网络
I have two classes where one derives the other. I also have a HashSet field which stores a bun开发者_运维知识库ch of Derived classes. The problem is that the Derived class is only used internally and

I have two classes where one derives the other. I also have a HashSet field which stores a bun开发者_运维知识库ch of Derived classes. The problem is that the Derived class is only used internally and I have a property which needs to return a HashSet of Base classes. I know List has the ConvertAll method, does HashSet have something similar?

public class Base
{
}

public class MyClass
{
    private class Derived : Base
    {
    }

    private HashSet<Derived> mList;

    public HashSet<Base> GetList { get { /* Convert mList to HashSet<Base> */ } }
}


You cannot convert a HashSet<Derived> to a HashSet<Base> without casting each item.

To explain why this is not possible, have a look at the following code example:

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>

However, since the IEnumerable interface is covariant, the following should be possible:

HashSet<Derived> mySet = ...;
IEnumerable<Base> x = mySet;  // works in C# 4

// no problem here, since no items can be added to an IEnumerable

Thus, you could change your method declaration:

public IEnumerable<Base> GetList { get { return mList; } }


Just declare mList as...

private HashSet<Base> mList;

You can do...

public HashSet<Base> GetList { get { return new HashSet<Base>(mList); } }

Since the mList implements IEnumerable<Base>


I don't think this is possible since HashSet is not covariant. It implements IEnumerable<T>, which is, but that restricts you to creating a new HashSet from the old one. They won't be kept in sync.

0

精彩评论

暂无评论...
验证码 换一张
取 消