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

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

发布时间:2020-12-15 21:42:51 所属栏目:百科 来源:网络整理
导读:在下面的示例中,为什么我不能将collectionA转换为collectionB,因为编译器知道TItem是A T? public class AT{}public void FooTItem,T () where TItem : AT{ var collectionA = new ListTItem(); var collectionB = (ListAT)collectionA; // "Cannot cast" er
在下面的示例中,为什么我不能将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.

(编辑:李大同)

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

    推荐文章
      热点阅读