1

代码例如:

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>

4

6 回答 6

2

这是我的方法:

IList<IArticle> articles = new List<Article>().Cast<IArticle>().ToList();
于 2012-09-22T09:32:04.170 回答
1

您可以使用 LINQ:

List<IArticle> articleList = ArticleBiz
    .GetArticles(2)
    .Where(p => p.cid == cid)
    .Cast<IArticle>()
    .ToList();
于 2012-09-22T09:25:25.130 回答
1

怎么样

List<IArticle> articleList = ArticleBiz.GetArticles(2).Where(p => p.cid == cid) 
                                       .Select(x => (IArticle)x).ToList();
于 2012-09-22T09:26:47.153 回答
1

您可以编写自己的隐式演员表。

public static implicit operator IArticle(Article article)
{
    return article;
}

另一种解决方案是编写显式转换运算符

///No need for an explicit cast though.
public static explicit operator IArticle(Article article)
{
    return (IArticle)article;
}

但是您能告诉我为什么要从数据库中返回 Articles 而不是 IArticle 对象吗?

于 2012-09-22T09:29:59.590 回答
0

希望,选择可以帮助你。

List<IArticle> articleList = ArticleBiz.GetArticles(2).FindAll(p => p.cid == cid)
                                       .Select(x => x as IArticle).ToList()
于 2012-09-22T09:19:34.810 回答
0

将 List 分配给 List 不起作用的原因是您可以执行以下操作:

class CrazyArticle : IArticle { ... }

List<Article> articles = ...
List<IArticle> iarticles = articles; // this is not actually legal

iarticles.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;
于 2012-09-22T14:08:59.503 回答