关于C#:如何从EventLogEntryType枚举中获取int值

How do I get the int value from the EventLogEntryType enum

本问题已经有最佳答案,请猛点这里访问。

我试图从EventLogEntryType枚举类型中获取数字代码。我有一个通用的日志方法,在调用我的数据库并将其记录到那里之前,它会将此作为消息的补充,并编写一个Windows事件日志。在将日志级别发送到数据库之前,我正在尝试检索日志级别的数字代码,以便按严重性对表中的这些消息进行排序。

不幸的是,事实证明这比我希望的要困难得多。以下是我的常规日志方法:

1
2
3
4
5
6
7
8
9
public static void MyGenericLogMessageMethod(string message, EventLogEntryType logLevel)
    {
    // Overwriting values for illustrative purposes
    logLevel = EventLogEntryType.Warning;    
    int logLevelCode = (int)logLevel.GetTypeCode();
    string testMessage ="Converted logLevel to logLevelCode [" + logLevelCode.ToString() +"]";
    eventLog.WriteEntry(testMessage, logLevel);
    //dssDatabaseDAO.LogMessage(message, logLevelCode);
    }

奇怪的是,产出是:

Converted logLevel to logLevelCode [9]

如果查看EventLogEntryType枚举类,则警告值为2,而不是9:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
namespace System.Diagnostics
{
    //
    // Summary:
    //     Specifies the event type of an event log entry.
    public enum EventLogEntryType
    {
        //
        // Summary:
        //     An error event. This indicates a significant problem the user should know about;
        //     usually a loss of functionality or data.
        Error = 1,
        //
        // Summary:
        //     A warning event. This indicates a problem that is not immediately significant,
        //     but that may signify conditions that could cause future problems.
        Warning = 2,
        //
        // Summary:
        //     An information event. This indicates a significant, successful operation.
        Information = 4,
        //
        // Summary:
        //     A success audit event. This indicates a security event that occurs when an audited
        //     access attempt is successful; for example, logging on successfully.
        SuccessAudit = 8,
        //
        // Summary:
        //     A failure audit event. This indicates a security event that occurs when an audited
        //     access attempt fails; for example, a failed attempt to open a file.
        FailureAudit = 16
    }
}

现在,我可以进入一个谩骂中,在Java中会变得简单和直接,但我不会,因为我知道我错了。也就是说,必须有更好或更正确的方法来检索我不知道的代码值。我已经查看了文档,但我要么缺少相关部分,要么不理解某些内容。

有人能给我指个方向吗?

谢谢您!


您只需要(int)logLevel—也就是说,您将loglevel转换为int。