代码示例:public Interface IArticle{ int cid{get;set;} string Name{get;set;} string Content{get;set;} ...}public Class Article:IArticle{ public int cid{get;set;} public string Name{get;set;} public string Content{get;set;} public string Extension{get;set;} ...}/*ArticleBiz.GetArticles(int cid) is select some items from database,return type:List<Article>*/List<IArticle> articleList=ArticleBiz.GetArticles(2).FindAll(p=>p.cid==cid)例外:Error 1 Cannot implicitly convert type 'System.Collections.Generic.List<Zm.Models.Article>'to 'System.Collections.Generic.IList<Zm.Models.IArticle>'.An explicit conversion exists (are you missing a cast?)问题:我不想在List<IArticle>方法中将返回类型更改为GetArticles(..)。如何更改代码以成功将List<Article>转换为List<IArticle>? 最佳答案 无法将列表分配给列表的原因是因为您可以执行以下操作:class CrazyArticle : IArticle { ... }List<Article> articles = ...List<IArticle> iarticles = articles; // this is not actually legaliarticles.Add(new CrazyArticle());// now either things should crash because we tried to add CrazyArticle to a List<Article>,// or we have violated type safety because the List<Article> has a CrazyArticle in it!这里至少有两个选择:(1)您可以使用LINQ Cast 运算符来构建IArticle类型的新列表:var iarticles = articles.Cast<IArticle>().ToList();(2)您可以更改为返回IEnumerable:// this is legal because IEnumerable<T> is declared as IEnumerable<out T>IEnumerable<IArticle> iarticles = articles;关于c# - 如何在C#3.5中将List <Article>转换为List <IArticle>,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12542502/
10-16 10:03