基于输入类型的C#8.0开关表达式

问题描述

是否可以根据输入类型在C#8中创建switch expression

我的输入类如下:

public class A1
{
    public string Id1 {get;set}
}

public class A2 : A1
{
    public string Id2 {get;set}
}

public class A3 : A1
{
    public string Id3 {get;set;}
}

我想基于输入类型(A1A2A3)运行不同的方法

var inputType = input.GetType();
var result = inputType switch
{
       inputType as A1 => RunMethod1(input); // wont compile,inputType as A2 => RunMethod2(input); // just showing idea
       inputType as A3 => RunMethod3(input);

}

但是它行不通。有什么想法如何根据输入类型创建switch或switch表达式吗?C

解决方法

您可以使用模式匹配,首先检查最具体的类型。

GetType是不必要的:

var result = input switch
{
    A2 _ => RunMethod1(input),A3 _ => RunMethod2(input),A1 _ => RunMethod3(input)    
};

但是,一种更面向对象的方法是在类型本身上定义一个方法:

public class A1
{
    public string Id1 { get; set; }
    public virtual void Run() { }
}

public class A2 : A1
{
    public string Id2 { get; set; }
    public override void Run() { }
}

然后就这么简单:

input.Run();
,

您可以,但是在这样的继承层次结构中,您需要从最具体的层次开始,然后向下移至最小的层次:

A1 inputType = new A2();
var result = inputType switch
{
    A3 a3 => RunMethod(a3),A2 a2 => RunMethod(a2),A1 a1 => RunMethod(a1)
};

请注意

  • inputType是一个实例,不是Type的一个实例
  • inputType被键入为基类,但可以是任何A1-3的实例。否则会出现编译器错误。

实时示例:https://dotnetfiddle.net/ip2BNZ