我有以下方法,它以类的类型作为参数:
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/