泛型List的继承

在.net2.0中 Class A:Class B

List<B> listB as List<A> ListA  不能通过编译器,你们是怎么解决的?

必须将listB 转换为 IList 或者 object ?


慕斯709654
浏览 405回答 2
2回答

慕码人8056858

lz明明说的是2.0嘛,哪里来的Cast方法?。。。lz可以自行编写一个Cast方法,遍历List<A>,把每个A转换成B,如&nbsp;static IEnumerable<TResult> Cast<TResult>(IEnumerable source) where TResult : class{ &nbsp; &nbsp;foreach (object o in source) &nbsp; &nbsp;{ &nbsp; &nbsp; &nbsp; &nbsp;TResult result = o as TResult; &nbsp; &nbsp; &nbsp; &nbsp;if (o == null) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;throw new InvalidCastException("can't cast"); &nbsp; &nbsp; &nbsp; &nbsp;yield return result; &nbsp; &nbsp;}}&nbsp;A虽然继承于B,但是List<A>与List<B>并不存在继承关系。&nbsp;

守着星空守着你

listB.Cast<A>().ToList()
打开App,查看更多内容
随时随地看视频慕课网APP