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

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

概述给定以下方法签名,为什么在显式命名参数时,编译器无法自动推断类型? Visual Studio 2010 SP1能够推断类型并且不显示警告或错误. IEnumerable<T> ExecuteCommand<T>( string commandText, string connectionName = null, Func<IDataRecord, T> converter 给定以下方法签名,为什么在显式命名参数时,编译器无法自动推断类型? 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编译器.

总结

以上是内存溢出为你收集整理的c# – 无法使用可选参数推断泛型类型全部内容,希望文章能够帮你解决c# – 无法使用可选参数推断泛型类型所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1243652.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存