我使用以下代码在我的代码中创建了一个可枚举的类:
public class ItemCollection : IEnumerable<AbstractItem>
{
private List<AbstractItem> Items;
public IEnumerator<AbstractItem> GetEnumerator()
{
return Items.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
效果很好,但我遇到了一个问题: AbstractItem有两个继承类,Book和Journal,它们都是从AbstractItem继承对象并拥有它们自己的一些(它们都得到了#34; Name&#34;来自AbstractItem,但只有Book有&#34; BGenre&#34;并且只有Journal有&#34; JTopic&#34;)因为我实现了AbstractItem的iEnumerator,我不能使用继承类在foreach循环中拥有的对象。我该如何解决?
答案 0 :(得分:3)
您可以使用 Linq 过滤掉Book
s,Journal
s:
ItemCollection collection = ...
var books = collection
.OfType<Book>();
var journals = collection
.OfType<Journal>();
例如,打印出所有BGenre
s:
String bGenres = String.Join(Environment.NewLine, collection
.OfType<Book>()
.Select(book => book.BGenre.ToString()));
Console.Write(bGenres);
答案 1 :(得分:1)
foreach (AbstractItem item in collection)
{
// common book and journal code here
if (item is Book)
{
// some code for books
}
else if (item is Journal)
{
// some code for journals
}
}
// another way:
List<Book> books = collection.OfType<Book>().ToList();
List<Journal> journals = collection.OfType<Journal>().ToList();
答案 2 :(得分:1)
您可以使用泛型:
public class ItemCollection<T> : IEnumerable<T>
{
private List<T> Items;
public IEnumerator<T> GetEnumerator()
{
return Items.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
然后你可以做类似的事情:
var books = new ItemCollection<Book>();
foreach(var book in books)
{
doSomething(book.BookProperty);
}
或
var journals = new ItemCollection<Journal>();
foreach(var journal in journals)
{
doSomething(journal.JournalProperty);
}
或访问摘要时
var items = new ItemCollection<AbstractItem>();
foreach(var item in items)
{
doSomething(item.AbstractItemProperty);
}
答案 3 :(得分:-1)
我不知道你是否在很好地实现你的抽象类。但在这种情况下,您可以使用反射来访问类的属性。像这样:
foreach (AsbtractClass Item in ItemCollection)
{
System.Reflection.PropertyInfo BGenre = Item.GetType().GetProperty("BGenre");
System.Reflection.PropertyInfo JTopic = Item.GetType().GetProperty("JTopic");
if (BGenre != null) TxtResultBGenre.Text = BGenre.GetValue(Item).ToString();
if (JTopic != null) TxtResultJTopic.Text = BGenre.GetValue(Item).ToString();
}
或者您可以分析Item的数据类型并获取已知属性。
foreach (AsbtractClass Item in ItemCollection)
{
if (Item is Book)
TxtResultBGenre.Text = System.Reflection.PropertyInfo BGenre = Item.GetType().GetProperty("BGenre").GetValue(Item).ToString();
else if (Item is Journal)
TxtResultJTopic.Text = System.Reflection.PropertyInfo JTopic = Item.GetType().GetProperty("JTopic").GetValue(Item).ToString();
}