因此,我有一个名为 LogEvent 的基础对象,并创建了其他派生自该对象的类,例如 ExecuteEvent 或 SubmitEvent。当我尝试获取特定实例的类型时,它们总是以 LogEvent 的形式返回。这是每个类的定义:
class LogEvent
{
public List<LogEventAttribute> eventAttributes = new List<LogEventAttribute>();
public int clusterId;
public DateTime eventTime;
public LogEvent(List<LogEventAttribute> eventAttributes)
{
this.eventAttributes = eventAttributes;
this.clusterId = Convert.ToInt32(eventAttributes.Find(p => p.name.Equals("Cluster")).value);
this.eventTime = DateTime.Parse(eventAttributes.Find(p => p.name.Equals("EventTime")).value);
}
}
class SubmitEvent : LogEvent
{
public string submitHost;
public SubmitEvent(List<LogEventAttribute> eventAttributes)
: base(eventAttributes)
{
this.submitHost = eventAttributes.Find(p => p.name.Equals("SubmitHost")).value;
}
}
class ExecuteEvent : LogEvent
{
public string executeHost;
public ExecuteEvent(List<LogEventAttribute> eventAttributes)
: base(eventAttributes)
{
this.executeHost = eventAttributes.Find(p => p.name.Equals("ExecuteHost")).value;
}
}
class TerminatedEvent : LogEvent
{
public bool successful;
public TerminatedEvent(List<LogEventAttribute> eventAttributes)
: base(eventAttributes)
{
this.successful = Convert.ToBoolean(eventAttributes.Find(p => p.name.Equals("TerminatedNormally")).value);
}
}
class LogEventAttribute
{
public string name, type, value;
public LogEventAttribute(string name, string type, string value)
{
this.name = name;
this.type = type;
this.value = value;
}
}
这里是我尝试根据类的类型做不同的事情的地方:
switch (currentEvent.GetType().ToString())
{
case "ExecuteEvent":
ExecuteEvent currentExEvent = currentEvent as ExecuteEvent;
item.SubItems.Add("Job executed by " + currentExEvent.executeHost);
break;
case "SubmitEvent":
SubmitEvent currentSubEvent = currentEvent as SubmitEvent;
item.SubItems.Add("Job submitted by " + currentSubEvent.submitHost);
break;
}
开关总是被忽略,因为 currentEvent.GetType().ToString() 总是出现在 LogEvent 中。
编辑:问题是我首先以不同的方式创建这些不同的类。这是错误的代码:
LogEventAttribute eventTypeAttribute = currentEventAttributes.Find(p => p.name.Equals("MyType"));
string eventType = eventTypeAttribute.type;
switch (eventType)
{
case "SubmitEvent":
logEvents.Add(new SubmitEvent(currentEventAttributes));
break;
case "ExecuteEvent":
logEvents.Add(new ExecuteEvent(currentEventAttributes));
break;
case "TerminatedEvent":
logEvents.Add(new TerminatedEvent(currentEventAttributes));
break;
default:
logEvents.Add(new LogEvent(currentEventAttributes));
break;
}
在我从 eventTypeAttribute 获取属性“type”的第二行,我应该获取 value 属性。我使用 type 属性来确定属性存储在其 value 属性中的值的类型。啊,TGIF。