Action和Func的重载分辨率不一致

时间:2016-03-21 17:34:49

标签: c#

考虑以下示例:

class Program
{
    private static void Main(string[] args)
    {
        Foo(() => { });
        Foo(() => { throw new Exception(); });
        Foo(() => { Throws(); });
        Foo(() => { throw new Exception(); return; });
        Foo(() => { throw new Exception(); return true; });
        Console.ReadLine();
    }

    public static void Foo(Action a)
    {
        Console.WriteLine("Foo(Action)");
    }

    public static void Foo(Func<bool> f)
    {
        Console.WriteLine("Foo(Func<bool>)");
    }

    public static void Throws()
    {
        throw new Exception();
    }
}

具有以下输出:

Foo(Action)
Foo(Func<bool>)
Foo(Action)
Foo(Action)
Foo(Func<bool>)

我很惊讶地注意到Foo(() => { throw new Exception(); });调用Foo(Func<bool> f)重载。我希望它能调用另一个重载。另请注意Foo(() => { throw new Exception(); return; });调用Foo(Action a)

此行为似乎不一致。我找不到这个的原因。看来,当编译器检测到lambda总是抛出时,它将支持Foo(Func<bool> f)重载,但是添加一个永远不会到达的return语句将改变行为。为什么它会像这样?

0 个答案:

没有答案