考虑以下事项:
void Main()
{
var list = new[] {"1", "2", "3"};
list.Sum(GetValue); //error CS0121
list.Sum(s => GetValue(s)); //works !
}
double GetValue(string s)
{
double val;
double.TryParse(s, out val);
return val;
}
CS0121错误的描述为:调用在以下方法或属性之间具有歧义:
'System.Linq.Enumerable.Sum<string>(System.Collections.Generic.IEnumerable<string>, System.Func<string,decimal>)'
和 'System.Linq.Enumerable.Sum<string>(System.Collections.Generic.IEnumerable<string>, System.Func<string,decimal?>
)'
我不理解的是,s => GetValue(s)
与简单的 GetValue
相比,会给编译器提供什么信息 - 是否后者只是前者的语法糖?
double D1(string s)
和int D1(string s)
,一个带有string M(string)
签名的方法组也会产生模棱两可的调用错误 - 即使这两个签名都不匹配。这与lambda不同,后者会尝试它们所有并在最后(或首次)尝试时给出转换错误。 - Ohad Schneider