我正在處理一個需要確定物件型別的專案,從該型別中獲取資訊并將其移動到適合我們資料庫的結構中。
為此,我將模式匹配與一個作業正常的 case 陳述句結合使用。
我唯一遇到的問題是某些型別也有嵌套型別。這些嵌套型別中的資訊就是我需要的資訊。
看看下面的代碼:
public class CallAnswered
{
public string Caller { get; set; }
public MetaDataInformation MetaData{ get; set; }
}
public class CallAbandoned
{
public string ReasonForAbandonment{ get; set; }
public MetaDataInformation MetaData { get; set; }
}
public class MetaDataInformation
{
public DateTime ReceivedAt { get; set; }
public DateTime AnsweredAt { get; set; }
}
public void DetermineType<T>(T callEvent)
{
switch (callEvent)
{
case CallAnswered callAnswered:
case CallAbandoned callAbandoned:
// Somehow, I need to access the "MetaData" property as a type
break;
}
}
如上面的代碼所示,我能夠檢測父型別并為其分配一個變數。但是我不知道如何獲取嵌套MetaDataInformation型別。
有誰知道如何解決這個問題?
uj5u.com熱心網友回復:
此處不需要泛型型別。通過從抽象基類派生,您可以解決兩個問題。
- 您可以使用基型別而不是泛型型別并訪問此基類的所有公共成員。
- 您可以在兩個派生類中實作的基類中添加抽象方法,從而使 switch 陳述句過時。
public abstract class Call
{
public MetaDataInformation MetaData { get; set; }
public abstract void Process();
}
public class CallAnswered : Call
{
public string Caller { get; set; }
public override void Process()
{
// TODO: Do Answer things. You can access MetaData here.
}
}
public class CallAbandoned : Call
{
public string ReasonForAbandonment{ get; set; }
public override void Process()
{
// TODO: Do Abandonment things. You can access MetaData here.
}
}
別的地方
public void ProcessCalls(Call callEvent)
{
// Replaces switch statement and does the right thing for both types of calls:
callEvent.Process();
}
這稱為多型行為。
也可以看看:
- 多型性(維基百科)
- 多型性 (Microsoft Docs)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/356471.html
下一篇:區分泛型類中泛型值的過濾陣列的項
