简体   繁体   English

无法使用实例引用访问System.Diagnostics.EventLog

[英]System.Diagnostics.EventLog Cannot be Accessed with an Instance Reference

I'm creating a Windows Service and have a slight issue when trying to write to the EventLog. 我正在创建Windows服务,尝试写入EventLog时有一个小问题。 I have the following code; 我有以下代码;

class WindowsService : ServiceBase
{
    public WindowsService()
    {
        ((ISupportInitialize)this.EventLog).BeginInit();

        if (!EventLog.SourceExists(this.ServiceName))
        {
            EventLog.CreateEventSource(this.ServiceName, "Application");
        }
        ((ISupportInitialize)this.EventLog).EndInit();
    }
}

This is based on the MSDN article and another SO question on here, and it worked up until last night however this morning it doesn't work with the error 这是基于MSDN文章以及此处的另一个SO问题,它可以解决直到昨晚,但是今天早晨它无法解决该错误

Member 'EventLog.SourceExists(string)' cannot be accessed with an instance reference; 成员'EventLog.SourceExists(string)'不能通过实例引用进行访问; qualify it with a type name instead 用类型名称代替它

Member 'EventLog.CreateEventSource(string, string)' cannot be accessed with an instance reference; 成员'EventLog.CreateEventSource(string,string)'不能通过实例引用进行访问; qualify it with a type name instead 用类型名称代替它

I'm not sure why, I've checked against a backup and that too is throwing an error. 我不知道为什么,我已经检查了备份,这也引发了错误。

Does anyone have any ideas? 有人有什么想法吗?

Thank you 谢谢

SourceExists and CreateEventSource are static methods, you need to qualify them with the type name rather than an instance variable. SourceExistsCreateEventSource是静态方法,您需要使用类型名称而不是实例变量来限定它们。 Based on the error and on this: 基于错误和基于此:

this.EventLog

presumably you have an instance variable called EventLog . 大概您有一个名为EventLog的实例变量。 Rename it to something less confusing, such as CurrentEventLog . 将其重命名为不太混乱的名称,例如CurrentEventLog Any meaningful name that doesn't conflict with an existing name. 现有名称不冲突的任何有意义的名称。

Basically, don't name your variables the same as their types. 基本上,不要将变量的名称与其类型相同。 That's just inviting confusion not only from the compiler but also from anybody who has to maintain that code. 这不仅会引起编译器的混乱,而且还会引起必须维护该代码的任何人的混乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM