因为 C# 无法在类型上切换
(据我所知,这并不是作为一种特殊情况添加的,因为 is
关系意味着不止一个不同的 case
可能适用),有没有比这更好的方法来模拟打开类型?
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());
}
}
最佳答案
With C# 7 ,随 Visual Studio 2017(版本 15.*)一起提供,您可以在 case
语句(模式匹配)中使用类型:
switch(shape)
{
case Circle c:
WriteLine($"circle with radius {c.Radius}");
break;
case Rectangle s when (s.Length == s.Height):
WriteLine($"{s.Length} x {s.Height} square");
break;
case Rectangle r:
WriteLine($"{r.Length} x {r.Height} rectangle");
break;
default:
WriteLine("<unknown shape>");
break;
case null:
throw new ArgumentNullException(nameof(shape));
}
在 C# 6 中,您可以将 switch 语句与 nameof() operator 一起使用(感谢@Joey Adams):
switch(o.GetType().Name) {
case nameof(AType):
break;
case nameof(BType):
break;
}
在 C# 5 及更早版本中,您可以使用 switch 语句,但您必须使用包含类型名称的魔术字符串...这对重构不是特别友好(感谢@nukefusion)
switch(o.GetType().Name) {
case "AType":
break;
}
关于c# - 有比 'switch on type' 更好的选择吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/298976/