【发布时间】:2020-10-13 08:04:53
【问题描述】:
是否可以根据输入类型在 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;}
}
我想根据输入类型(A1、A2 或 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);
}
但它不会工作。任何想法如何根据输入类型创建开关或开关表达式?C
【问题讨论】:
-
尝试首先使用最具体的类型 (A3) 启动开关,然后逐步降低到最不具体的 (A1)
-
但我的代码无法编译,我只是展示了想法
-
哦,我现在看到了,替换为 is