代码之家  ›  专栏  ›  技术社区  ›  Armstrongest

传递实现同一接口的不同内容

  •  3
  • Armstrongest  · 技术社区  · 15 年前

    我有多个Linq2Sql类,比如“Article”“NewsItem”“Product”。

    他们都有一个标题,他们都有一个唯一的ID,他们都有一个摘要。

    所以,我创建了一个名为 IContent

    public interface IContent {
        int Id { get; set; }
        String Title { get; set; }
        String Summary { get; set; }
        String HyperLink { get; set; }
    }
    

    List<T> 实现 I内容 然后使用我在项目的每个分部类中实现的公共属性。

    Article 是Linq实体。 我创建一个分部类并实现

       #region IContent Members
    
        public int Id {
            get {
                return this.ArticleID;
            }
            set {
                this.ArticleID = value;
            }
        }
    

    很简单。在我的代码中,我试图这样做,但我不知道我错在哪里:

    List<IContent> items;
    
    MyDataContext cms = new MyDataContext();
    
    items = cms.GetArticles();  
    // ERROR: Can not implicitly convert List<Article> to List<IContent>
    

    如果我的 文章 类实现 为什么我不能把文章传下去?我不知道将要传入的对象是什么。

    我知道我可以通过继承基类来做到这一点,但是使用LinqToSQL不使用常规对象。

    3 回复  |  直到 15 年前
        1
  •  1
  •   code4life    15 年前

    你试过了吗

    items = cms.GetArticles().Cast<IContent>().ToList();  
    
        2
  •  7
  •   Lucero    15 年前
        3
  •  1
  •   Igor Zevaka    15 年前

    List<Article> IEnumerable<Article>

    IEnumerable<IContent> articles = myContext.GetArticles();
    

    如果你被.NET3.5困住了,你可以直接使用Linq Cast<T>()

    IEnumerable<IContent> articles = myContext.GetArticles().Cast<IContent>();