开发者

List to IEnumerable with parent and child class

开发者 https://www.devze.com 2023-03-28 02:48 出处:网络
Given the following classes: public class ContentItem : IEquatable<ContentItem> { ... } and public class Widget : ContentItem, IWidget

Given the following classes:

public class ContentItem : IEquatable<ContentItem>
{
...
}

and

public class Widget : ContentItem, IWidget
{
...
}

why I can't do this:

List<Widget> widgets = _repository.GetItems(widgetType);

where

_repository.GetItems(widgetType) returns IEnumerable<ContentItem>?

Essentially I already have a repository implementation which works on ContentItem class and I would like to use that same repository also for working with Widget class basically because Widget has the same base开发者_开发技巧 properties and only introduces few new ones that just hold some information (they come from IWidget interface) and don't have any impact on how repository should handle the class). I don't want to make another repository class just to replace all occurences of ContentItem with Widget.

Should I make my changes by explicitly specifing casts or changing my repository (or repository interface, which I also have)? If possible, I would like to avoid various constructs such as AsEnumerable(), ToList() or explicit casts.


Because a ContentItem is not a Widget - it's the other way round. Even then an IEnumerable<ContentItem> is different from a List<Widget>, you can achieve what you want by doing something like this:

List<Widget> widgets = _repository.GetItems(widgetType)
                                  .OfType<Widget>()
                                  .ToList();

But this will only work if you are really returning an enumeration where each ContentItem is really a Widget.

0

精彩评论

暂无评论...
验证码 换一张
取 消