C#切换类的类型

LmC*_*LmC 2 c# if-statement typeof switch-statement

我有以下方法,它将一种类作为参数:

public void test(Type proType){

}
Run Code Online (Sandbox Code Playgroud)

我目前有一个大的if else看起来像:

if(proType == typeof(Class)){}
Run Code Online (Sandbox Code Playgroud)

因为大约有十个看起来不整洁.

我尝试将其转换为开关但无法使其工作.

有没有更好的做法可以让这个或那个让switch语句工作?

           switch (proType)
            {
                case typeof(ClassName):
                    break;
            }
Run Code Online (Sandbox Code Playgroud)

"需要恒定值"

该函数被称为 test(typeof(class))

所以目标是我有一个包含许多小类的Big对象.

typeof(class)switch/if语句允许我决定进入哪个容器来获取对象.

spe*_*der 7

那么,如何让你正在测试的所有对象共享一个共同的界面呢?

 interface ITestable
 {
     void DoSomething();
 }
Run Code Online (Sandbox Code Playgroud)

并且每个对象以不同方式实现此接口

 class MySomething : ITestable
 {
     public void DoSomething()
     {
         //type specific implementation
     }
 }

 class MyOtherSomething : ITestable
 {
     public void DoSomething()
     {
         //type specific implementation
     }
 }
Run Code Online (Sandbox Code Playgroud)

现在:

 foreach(ITestable testable in myTestablesList)
 {
     testable.DoSomething();
 }
Run Code Online (Sandbox Code Playgroud)

并且所有切换逻辑都消失了.田田!