【问题标题】:Why foreach var in EventLogEntryCollection not returning EventLogEntry?为什么 EventLogEntryCollection 中的 foreach var 不返回 EventLogEntry?
【发布时间】:2019-09-05 06:11:51
【问题描述】:

我对 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】:

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

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

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

    但是,如果我将 var 更改为 EventLogEntry,它会按照我使用 for 循环的方式工作。

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

    另见Object type not recognised on foreach loop

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多