无法使用可选参数推断泛型类型

Jos*_*hua 7 c# type-inference optional-parameters

给定以下方法签名,为什么在显式命名参数时,编译器无法自动推断类型?Visual Studio 2010 SP1能够推断类型并且不显示警告或错误.

IEnumerable<T> ExecuteCommand<T>(
    string commandText,
    string connectionName = null,
    Func<IDataRecord, T> converter = null) { ... }

static SomeClass Create(IDataRecord record) { return new SomeClass(); }

void CannotInferType() {
    var a = ExecuteCommand(
        "SELECT blah",
        "connection",
        converter: Test.Create);
}

void CanInferType() {
    var a = ExecuteCommand(
        "SELECT blah",
        "connection",
        Test.Create);
}
Run Code Online (Sandbox Code Playgroud)

按照中所述调用它CannotInferType并在尝试编译它时,编译器会按照预期的方式error CS0411: The type arguments for method 'Test.ExecuteCommand<T>(string, string, System.Func<System.Data.IDataRecord,T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.调用它来调用它CanInferType.

如上所述,Visual Studio本身没有报告任何问题,并且变量的intellisense a显示IEnumerable<SomeClass>为预期但由于某种原因它不能编译.

Jon*_*eet 7

这是C#4编译器中的一个错误.它已在C#5编译器中修复.

我怀疑它不是导致问题的可选参数 - 它是命名参数.尝试删除参数的默认值,我怀疑你仍然会遇到同样的问题.(值得区分可选参数和命名参数 - 它们是两个独立的功能.它们经常一起使用,但肯定不一定.)

这是我在向Eric和Mads发送此错误报告时得出的结论:

using System;

class Test
{
    static void Foo<T>(Func<T> func) {}

    static void Main()
    {
        // Works fine
        Foo(() => "hello");

        // Type inference fails
        Foo(func: () => "hello");
    }
}
Run Code Online (Sandbox Code Playgroud)

令人高兴的是,这现在适用于C#5 beta编译器.