2012-09-22 74 views
1

代碼例如:如何轉換列表<Article>列出<IArticle>在C#3.5

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>

回答

0

該分配列表到列表不工作的原因是,那麼你可以做到以下幾點:

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建立一個新的類型列表列表<>運算符:

var iarticles = articles.Cast<IArticle>().ToList(); 

(2)你可以改變返回的IEnumerable:

// this is legal because IEnumerable<T> is declared as IEnumerable<out T> 
IEnumerable<IArticle> iarticles = articles; 
0

希望,選擇可以幫助你。

List<IArticle> articleList = ArticleBiz.GetArticles(2).FindAll(p => p.cid == cid) 
             .Select(x => x as IArticle).ToList() 
1

你可以使用LINQ:

List<IArticle> articleList = ArticleBiz 
    .GetArticles(2) 
    .Where(p => p.cid == cid) 
    .Cast<IArticle>() 
    .ToList(); 
1

如何

List<IArticle> articleList = ArticleBiz.GetArticles(2).Where(p => p.cid == cid) 
             .Select(x => (IArticle)x).ToList(); 
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; 
} 

,你能告訴我你爲什麼從數據庫中,而不是IArticle對象返回文章?

2

這裏是我的方法:

IList<IArticle> articles = new List<Article>().Cast<IArticle>().ToList(); 
相關問題