无法推断带有可选参数的通用类型 [英] Unable to infer generic type with optional parameters

查看:65
本文介绍了无法推断带有可选参数的通用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Given the following method signature, why is it when a parameter is explicitly named the compiler is unable to automatically infer the type? Visual Studio 2010 SP1 is able to infer the type and shows no warnings or errors.

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);
}

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中所述进行调用则按预期进行.

Calling it as described in CannotInferType and when attempting to compile it the compiler emits 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. Whereas calling it as described in CanInferType works as expected.

如上所述,Visual Studio本身未报告任何问题,并且变量a的智能感知按预期显示了IEnumerable<SomeClass>,但由于某种原因它无法编译.

As stated above, Visual Studio itself reports no problems, and intellisense for the variable a shows IEnumerable<SomeClass> as expected but for some reason it doesn't compile.

推荐答案

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

It was a bug in the C# 4 compiler. It's been fixed in the C# 5 compiler.

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

I suspect it's not the optional parameter which is causing the problem here - it's the named argument. Try removing the default values for your parameters and I suspect you'll still have the same problem. (It's worth differentiating between optional parameters and named arguments - they're two separate features. They're often used together, but certainly don't have to be.)

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

That's the conclusion I came to when I sent this bug report to Eric and 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");
    }
}

现在,这在C#5 beta编译器中可以正常工作了.

Happily this now works in the C# 5 beta compiler.

这篇关于无法推断带有可选参数的通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆