为什么在EventLogEntryCollection中foreach var没有返回EventLogEntry?

问题描述 投票:0回答:1

我研究了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);
        }
c# collections system.diagnostics
1个回答
3
投票

为什么在foreach循环中使用的EventLogEntryCollection不返回EventLogEntry

因为它是旧代码,预先泛型。它merely implements ICollection,它继承了你的IEnumerable.GetEnumerator() method循环使用的非泛型foreach()

所以该枚举器的项类型是object,并且不包含Message属性。

但是,如果我将var更改为EventLogEntry,它的工作方式与我预期的循环方式相同。

这正是你需要做的解决这个问题的方法。

另见Object type not recognised on foreach loop

© www.soinside.com 2019 - 2024. All rights reserved.