我在使用 c# 的模式匹配功能时偶然发现了一个缺失的警告。通常编译器在检测无法访问的代码方面非常聪明,所以我想知道为什么这不会生成警告:
internal interface IAction{}
internal class Increment : IAction{}
internal class Decrement : IAction{}
internal class DoNothing{}
internal class Program
{
private static void Main(string[] args)
{
// obviously the following will not compile:
// Console.Write(Dispatch(5, new DoNothing()));
Console.Write(Dispatch(5, new Increment()));
}
private static int Dispatch(int value, IAction action)
{
switch (action)
{
case Increment _:
return value + 1;
case Decrement _:
return value - 1;
case DoNothing _: // Not an IAction, will never happen, but no warning is generated
return value;
default:
return value;
}
}
}
可能会有一个MyDoNothing
internal class MyDoNothing : DoNothing, IAction {}
它既是DoNothing
也是IAction
,因此可以传递给Dispatch
方法。如果密封DoNothing
类,则会出现编译时错误。
每个 case 语句等效于
if (action is SOMETHING)
操作很可能是无所事事和 IAction,如下所示:
public DoNothingEx : DoNothing, IAction{}