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

C#为什么我不能添加一个类型到子类的哈希集到一个类型为其超类的

发布时间:2020-12-15 06:57:34 所属栏目:百科 来源:网络整理
导读:为什么在下面的代码中得到一个编译错误(请参阅注释行)? public void Test() { HashSetHashSetAnimal setWithSets = new HashSetHashSetAnimal(); HashSetCat cats = new HashSetCat(); setWithSets.Add(cats); // Compile error } private class Animal { }
为什么在下面的代码中得到一个编译错误(请参阅注释行)?
public void Test()
    {
        HashSet<HashSet<Animal>> setWithSets = new HashSet<HashSet<Animal>>();
        HashSet<Cat> cats = new HashSet<Cat>();
        setWithSets.Add(cats); // Compile error
    }

    private class Animal { }

    private class Cat : Animal { }

VS2012给了我两个错误,第一个是重要的一个:

>错误2参数1:无法从“System.Collections.Generic.HashSet&Expenses.Tests.TestDb.SetTest.Cat”转换到’System.Collections.Generic.HashSet&Expenses.Tests.TestDb.SetTest.Animal>’
>错误1最好的重载方法匹配’System.Collections.Generic.HashSet< System.Collections.Generic.HashSet&Expenses.Tests.TestDb.SetTest.Animal> .Add(System.Collections.Generic.HashSet)’有一些无效的参数

我的问题是:为什么我不能在“setWithSets”中添加“cats”?

解决方法

为了更好地理解为什么不允许这样做,请考虑以下程序.

行setOfSets.First().Add(new Dog());是编译器可以接受的,因为动物的集合肯定可以容纳一个Dog的实例.问题是集合中第一集合的动物是Cat实例的集合,而Dog不扩展Cat.

class Animal { }
class Cat : Animal { }
class Dog : Animal { }

class Program {
    static void Main(string[] args) {

        // This is a collection of collections of animals.
        HashSet<HashSet<Animal>> setOfSets = new HashSet<HashSet<Animal>>();

        // Here,we add a collection of cats to that collection.
        HashSet<Cat> cats = new HashSet<Cat>();
        setOfSets.Add(cats);

        // And here,we add a dog to the collection of cats. Sorry,kitty!
        setOfSets.First().Add(new Dog());
    }
}

(编辑:李大同)

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

    推荐文章
      热点阅读