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

mic*_*cer 3 c# c#-8.0

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

我的输入类如下所示:

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;}
}
Run Code Online (Sandbox Code Playgroud)

我想根据输入类型运行不同势方法(A1A2,或A3):

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);

}
Run Code Online (Sandbox Code Playgroud)

但它不会工作。任何想法如何根据输入类型创建 switch 或 switch 表达式?C

Joh*_*lay 5

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

GetType 是不必要的:

var result = input switch
{
    A2 _ => RunMethod1(input),
    A3 _ => RunMethod2(input),
    A1 _ => RunMethod3(input)    
};
Run Code Online (Sandbox Code Playgroud)

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

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() { }
}
Run Code Online (Sandbox Code Playgroud)

那么它很简单:

input.Run();
Run Code Online (Sandbox Code Playgroud)