我研究了IEnumerable和IEnumerator,有很多关于如何使类可用于foreach语句的方法。但这并没有回答我的问题。为什么foreach循环中使用的EventLogEntryCollection不返回EventLogEntry?但是,如果我将var更改为EventLogEntry,它的工作方式与我预期的for循环方式相同。
EventLog eventLog1 = new EventLog
{
Log = myLogName,
Source = "sourcy"
};
EventLogEntryCollection collection = eventLog1.Entries;
eventLog1.Close();
foreach (var v in collection)
{
Console.WriteLine(v.Message); //object does not contain definition for Message
}
for (int i = 0; i < collection.Count; i++)
{
Console.WriteLine("The Message of the EventLog is :"
+ collection[i].Message);
}
为什么在foreach循环中使用的
EventLogEntryCollection
不返回EventLogEntry
?
因为它是旧代码,预先泛型。它merely implements ICollection
,它继承了你的IEnumerable.GetEnumerator()
method循环使用的非泛型foreach()
。
所以该枚举器的项类型是object
,并且不包含Message
属性。
但是,如果我将var更改为
EventLogEntry
,它的工作方式与我预期的循环方式相同。
这正是你需要做的解决这个问题的方法。