【发布时间】:2017-10-08 09:16:02
【问题描述】:
我正在尝试从 EventLogEntryType 枚举类型中获取数字代码。我有一个通用的日志方法,除了消息之外,它还会在调用我的数据库之前写入一个 Windows 事件日志以将其记录到那里。在将日志级别发送到数据库之前,我会尝试检索日志级别的数字代码,以便可以按严重性对表中的这些消息进行排序。
不幸的是,事实证明这比我希望的要困难得多。以下是我的通用日志方法:
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);
}
输出结果很奇怪:
将 logLevel 转换为 logLevelCode [9]
如果您查看EventLogEntryType 枚举类,Warning 的值是 2,而不是 9:
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 中会变得多么简单和直接,但我不会,因为我知道我错了。也就是说,必须有一种更好或更正确的方法来检索我不知道的代码值。我查看了文档,但我要么遗漏了相关部分,要么不理解某些内容。
有人可以指点我正确的方向吗?
谢谢!
【问题讨论】:
-
只需摆脱
GetTypeCode()调用并将枚举转换为int:int logLevelCode = (int)logLevel; -
仅供参考,
GetTypeCode返回一个名为TypeCode 的不同 枚举,它表示您正在处理的对象的类型。由于枚举表示为整数,因此在您的示例中,这就是9的来源:(int)TypeCode.Int32 = 9 -
好的 - 因为我不熟悉阅读和理解 C# 文档 - 甚至再次查看它,在我看来并没有立即明显看出这是解决方案。为什么我需要对枚举对象有隐含的了解才能进行转换?为什么没有像 java 中那样有一个访问器方法,它会明确地告诉你值的类型,同时提供一个检索它的方法?
-
@Muckeypuck 你是对的 - 我似乎错过了其他帖子。这可能是不知道如何提出正确问题的情况。我很感激!
-
您所问的问题具有广泛的意义,但有一个潜在的主题(尤其是在您随后的回答中)“为什么 C# 与 Java 不同?”。这对你没有帮助,真的。您可能会问“为什么 Java 与 C# 不同?”。它们只是不同,也不是另一个的“版本”。