Transferring other content that implements the same interface

I have several Linq2Sql classes, such as "Article" "NewsItem" "Product".

They all have a title, they all have a unique identifier, and they all have a summary.

So, I created an interface called IContent

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

In my code, I try to pass List<T>, which implements IContent, and then use the general properties that I implemented in each of the partial classes in my project.

So, just to clarify

Article- Linq object. I create a partial class and implement IContentHere a fragment of the .cs article:

   #region IContent Members

    public int Id {
        get {
            return this.ArticleID;
        }
        set {
            this.ArticleID = value;
        }
    }

Pretty simple. In my code, I am trying to do this, but I do not know where I am going wrong:

List<IContent> items;

MyDataContext cms = new MyDataContext();

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

Article IContent, ? , .

, , LinqToSQL .

, - , .

+3
3

items = cms.GetArticles().Cast<IContent>().ToList();  
+1

, List . .NET 4.0 # 4.0, IEnumerable<>, LINQ.

FAQ, .

+7

, # 4.0. List<Article> IEnumerable<Article>, assignemnt :

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

If you are stuck with .NET 3.5, you can just use Linq Cast<T>():

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

Source: https://habr.com/ru/post/1762754/


All Articles