看作C#无法打开一个Type(我收集的并不是作为特殊情况添加的,因为is-a关系意味着可能有多个不同的情况可能适用),是否有更好的方法来模拟切换类型?
void Foo(object o)
{
if (o is A)
{
((A)o).Hop();
}
else if (o is B)
{
((B)o).Skip();
}
else
{
throw new ArgumentException("Unexpected type: " + o.GetType());
}
}
Run Code Online (Sandbox Code Playgroud) 下面是开关盒
switch (strID)
{
case ConfigurationManager.AppSettings["Key1"].ToString():
Label1.Visible = true;
break;
case ConfigurationManager.AppSettings["Key2"].ToString():
Label2.Visible = true;
break;
case ConfigurationManager.AppSettings["Key3"].ToString():
Label3.Visible = true;
break;
default:
Label1.Visible = true;
break;
}
Run Code Online (Sandbox Code Playgroud)
但它给出了错误“期望一个常数值”。
我知道 switch 语句中不能有变量。但是有什么办法吗?