检测泛型的嵌套类型

Detect nested type of generic

我正在开展一个项目,该项目需要确定对象的类型,从该类型中获取信息并将其移动到适合我们数据库的结构中。

为此,我将模式匹配与 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 类型。

有人知道如何解决这个问题吗?

这里不需要通用类型。通过从抽象基础派生 class,您可以解决两个问题。

  1. 您可以使用基类型而不是泛型类型,并访问该基 class.
  2. 的所有 public 成员
  3. 您可以在两个派生 class 中实现的基础 class 中添加一个抽象方法,从而使 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();
}

这称为多态行为。

另请参阅: