铸造Templete内在价值问题 [英] Casting in Templete inner value problems

查看:214
本文介绍了铸造Templete内在价值问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能分享我的code BU基本上我有一个类实现接口,像这样:

 公共接口
{
    无效DOA();
}

公共类B:
{
    公共无效DOA()
    {
     //做
    }
}
 

和我有一个像这样的列表:

 名单,其中,B>名单=新的名单,其中,B>();
list.Add(新的B());
 

现在我希望有一个的IEnumerable< A> 。所以我想这3行:

 名单,其中,A> listCast =(名单< A>)名单;
IEnumerable的< A> listCastToEnumerable =(IEnumerable的< A>)名单;
IEnumerable的< A> listCastExt = list.Cast< A>();
 

  1. 在第一个得到了一个错误:
  

错误1无法将类型   System.Collections.Generic.List< WindowsFormsApplication1.B> 来   System.Collections.Generic.List< WindowsFormsApplication1.A>

  1. 第二个没有得到一个错误,但得到了 InvalidCastException的

  2. 第三项工作。

我的问题是:

  1. 为什么第一线得到一个错误,而第二行没有?
  2. 为什么前两个内衬是无效的?
  3. 什么是做这种投的最好方法?是三线好了还是有一些更好的方法
解决方案

让我们打破它。

1 为什么第一线得到一个错误,而第二行没有?

在您铸造到第二行的的IEnumerable(T)这是协变的。

2 为什么前两个内衬是无效的?

即使你投你的名单,其中,B> 它仍然保持其基本类型的信息,这意味着它不能持有型这是B型的不也是项目一

3。什么是做这种投的最好方法?是三线好了还是有一些更好的方法

第三行蒙上了列表中的每个元素为A型,并返回一个新的的IEnumerable(T) A型。这可以迭代到一个新的列表 A型,这将愉快地持有型的任何元素。

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

解决方案

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.

这篇关于铸造Templete内在价值问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆