首页 新闻 赞助 找找看

为什么 List<Object> 无法转换成 List<Interface>?

0
悬赏园豆:50 [已解决问题] 解决于 2015-02-17 14:15
using System.Collections.Generic;
using System.Linq;

namespace Console1
{
    public interface IPerson
    {
        int Id { get; set; }
        string Name { get; set; }
    }

    public static class IPersonExtensions
    {
        public static string GetFullText(this List<IPerson> source)
        {
            return source.Aggregate("", (text, item) => text + ' ' + item.Name);
        }
    }

    public class Person : IPerson
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }

    internal class TextProgram
    {
        private static void Main1(string[] args)
        {
            var persons = new List<Person>
            {
                new Person {Id = 1, Name = "Wang"}, 
                new Person {Id = 2, Name = "Sun"}
            };

            var text = persons.GetFullText();

        }
    }
}

以上是我的测试代码,最后一行会提示错误:

实例参数: 无法从“System.Collections.Generic.List<Console1.Person>”转换为“System.Collections.Generic.List<Console1.IPerson>”

我的 Person 明明是继承自 IPerson,为什么无法转换呢?

问题补充:

呃,原来是C#不支持。。。好衰。。。

那么,List<> 可以用 ConvertAll 转换,IList<> 或者 ICollection<> 或者 IEnumerable<> 有相应的语句吗?

东至的主页 东至 | 初学一级 | 园豆:16
提问于:2015-02-17 12:34
< >
分享
最佳答案
0

Person可以转化为IPerson,但是放在List里面就不可以。

要么你就等使用最新版的C#或者等待微软开发这个强制转换。

要么你自己转换一下

var text = persons.ConvertAll(x=>(IPerson)x).GetFullText();

看看,这也不是多么费劲的事。

收获园豆:30
爱编程的大叔 | 高人七级 |园豆:30839 | 2015-02-17 12:45

呃,原来是C#不支持。。。好衰。。。

那么,List<> 可以用 ConvertAll 转换,IList<> 或者 ICollection<> 或者 IEnumerable<> 有相应的语句吗?

东至 | 园豆:16 (初学一级) | 2015-02-17 12:52
其他回答(4)
1

IEnumerable<Person> d = new List<Person>();

IEnumerable<IPerson> b = d;

收获园豆:10
Launcher | 园豆:45045 (高人七级) | 2015-02-17 13:00
0
static IEnumerable<I> ConvertFrom<T, I>(List<T> items) where T : I
            {
                  foreach (I item in items) yield return item;
            }


List<Apple> apples = new List<Apple> { new Apple()};                  
List<IFruit> fruit = ConvertFrom<Apple, IFruit>(apples).ToList();
收获园豆:10
Yu | 园豆:12980 (专家六级) | 2015-02-17 13:33
0

List<Console1.Person>不是继承于List<Console1.IPerson>,它俩都是继承于List<T>。至于位什么不支持这样的转换,可以去看看泛型的逆变性和协变性。

守望雲影 | 园豆:14 (初学一级) | 2015-02-19 20:53
0

不错,协变逆变可以搞定,推荐牛人文章http://www.cnblogs.com/LoveJenny/archive/2012/03/13/2392747.html

arg | 园豆:1047 (小虾三级) | 2015-02-20 13:47
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册