类类型的 C# 开关

标签 c# if-statement switch-statement typeof

我有以下方法,它以类的类型作为参数:

public void test(Type proType){

}

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

if(proType == typeof(Class)){}

因为大约有 10 个,所以看起来不整洁。

我试着把它变成一个开关,但无法让它工作。

是否有更好的做法来让 switch 语句起作用?

           switch (proType)
            {
                case typeof(ClassName):
                    break;
            }

“需要一个常量值”

函数被调用为 test(typeof(class))

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

typeof(class) switch/if 语句允许我决定进入哪个容器以取出对象。

最佳答案

那么,让您正在测试的所有对象共享一个公共(public)接口(interface)怎么样?

 interface ITestable
 {
     void DoSomething();
 }

并且每个对象都以不同的方式实现这个接口(interface):

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

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

现在:

 foreach(ITestable testable in myTestablesList)
 {
     testable.DoSomething();
 }

所有的切换逻辑都消失了。多田!

关于类类型的 C# 开关,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19117882/

相关文章:

c# - 我怎样才能在 excel epplus c# 中换行

c# - IProducerConsumerCollection<T>.TryAdd/.TryTake - 他们什么时候返回 true/false?

Bash - 检查哪个变量不等于零

java - charAt 无法在 Java 分数计算器中工作

c++ - 为什么 C++ switch 语句仅限于常量表达式?

c# - 使用特定的 Langdriver 在 .Net 中编写 Paradox 表

c# - 在按钮 ASP.NET c# 上禁用回发

javascript - 如果字符串以数字开头,则检查字符串的长度

c - 在开关盒中将 int 与 int 数组的元素匹配

java - 在 switch 语句内循环或在循环内使用 switch 语句更有效?