加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 07:45:49 所属栏目:百科 来源:网络整理
导读:给定以下方法签名,为什么在显式命名参数时,编译器无法自动推断类型? Visual Studio 2010 SP1能够推断类型并且不显示警告或错误. IEnumerableT ExecuteCommandT( string commandText,string connectionName = null,FuncIDataRecord,T converter = null) { ..
给定以下方法签名,为什么在显式命名参数时,编译器无法自动推断类型? 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",Test.Create);
}

按照在EnsureInferType中的描述调用它,当尝试编译它时编译器发出错误CS0411:方法’Test.ExecuteCommand< T>(字符串,字符串,System.Func< System.Data.IDataRecord,T>)’的类型参数不能从用法推断.尝试显式指定类型参数.而CanInferType中描述的调用它按预期工作.

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

解决方法

这是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");
    }
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读