我不认为我在做任何太深奥的事情,但我没有看到任何其他关于此的问题。
以下代码(我已将其简化为基本代码)在 C# 4 中生成编译器错误。但是,类型参数是什么应该是显而易见的 - 有一个最大公分母(“A 类”)也明确定义在方法“Frob”的返回类型。编译器不应该列出 lambda 表达式中的所有返回类型,创建一个祖先树来查找它们的共同祖先,然后将其与包含方法的预期返回类型相协调吗?
无法从用法中推断方法“System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)”的类型参数。尝试明确指定类型参数。
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Sample
{
    public abstract class A
    {
        private A(int index) { /* ... */ }
        public sealed class A1 : A
        {
            public A1(string text, int index)
                : base(index)
            { /* ... */ }
        }
        public sealed class A2 : A
        {
            public A2(int index)
                : base(index)
            { /* ... */ }
        }
        private static Regex _regex = new Regex(@"(to be)|(not to be)");
        public static IEnumerable<A> Frob(string frobbable)
        {
            return _regex.Matches(frobbable)
                .Cast<Match>()
                .Select((match, i) =>
                {
                    if (match.Groups[1].Success)
                    {
                        return new A1(match.Groups[1].Value, i);
                    }
                    else
                    {
                        return new A2(i);
                    }
                });
        }
    }
}