所以,我有一個名爲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屬性中存儲的值的類型。阿格,TGIF。
請嘗試使用'currentEvent.GetType()。Name'來代替。 –
因爲它是一個LogEvent – Jared
@Chris,這也出來LogEvent – stereoa