Casting in Templete inner value problems

爱⌒轻易说出口 提交于 2019-12-12 00:23:41

问题


I can't share my code bu basically i have a class implementing interface like so:

public interface A
{
    void doA();
}

public class B: A
{
    public void doA()
    {
     // Doing A
    }
}

and i have a list of A like so:

List<B> list = new List<B>();
list.Add(new B());

now i want an IEnumerable<A>. so i tried these 3 lines:

List<A> listCast = (List<A>)list;
IEnumerable<A> listCastToEnumerable = (IEnumerable<A>)list;
IEnumerable<A> listCastExt = list.Cast<A>();
  1. The first one got an error:

"Error 1 Cannot convert type 'System.Collections.Generic.List<WindowsFormsApplication1.B>' to 'System.Collections.Generic.List<WindowsFormsApplication1.A>'".

  1. The second did not got an error but got InvalidCastException.

  2. The third one worked.

My questions are:

  1. Why did the first line got an error while the second line didn't?
  2. Why did the first two lined aren't valid?
  3. What's the best way to do this kind of cast? is the third line good for that or is there some better way

回答1:


Lets break it down.

1. Why did the first line got an error while the second line didn't?

On the second line you're casting to an IEnumerable(T) which is covariant.

2. Why did the first two lined aren't valid?

Even when you cast your List<B> it is still keeps its underlying type information which means it cannot hold items of type A which are not also of type B.

3. What's the best way to do this kind of cast? is the third line good for that or is there some better way

The third line casts each element of the List into type A and return a new IEnumerable(T) of type A. This can be iterated into a new List of type A which will happily hold any element of type A.




回答2:


You can also do

 IEnumerable<A> listoftypeb = list.OfType<A>();

This will give you a list of A without an error if you have an element that can't be case to type A




回答3:


you need to create an IEnumerable(T) and populate it with your data from your list, because List<B> is not IEnumerable<A>



来源:https://stackoverflow.com/questions/17447491/casting-in-templete-inner-value-problems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!