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

c# – 在通用集合之间转换

在下面的示例中,为什么我不能将collectionA转换为collectionB,因为编译器知道TItem是A< T>?

public class A<T>
{
}

public void Foo<TItem,T> () where TItem : A<T>
{
    var collectionA = new List<TItem>();
    var collectionB = (List<A<T>>)collectionA; // "Cannot cast" error here
}

解决方法

问题是,它允许您将不适当的项目放入collectionA.

这是对它的简化改造,希望能够更容易地看到问题:

假设你有(伪代码):

class Animal {...}

class Dog: Animal { Bark(){} }

class Cat: Animal { Meow(){} }

现在假设你可以这样做:

var dogs = new List<Dog>();

dogs.Add(new Dog());

dogs[0].Bark();

var animals = (List<Animal>) dogs;

然后你就可以这样做:

animals.Add(new Animal()); // Adds an Animal to the list 'dogs',which 'animals' references.

dogs[1].Bark(); // dogs will Now have two elements,but the second isn't a dog -
                // so calling Bark() will explode.

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

相关推荐