dah*_*byk 9 c# delegates type-inference
我有一个Money带有隐式转换的简单类型decimal:
struct Money
{
decimal innerValue;
public static implicit operator Money(decimal value)
{
return new Money { innerValue = value };
}
public static explicit operator decimal(Money value)
{
return value.innerValue;
}
public static Money Parse(string s)
{
return decimal.Parse(s);
}
}
Run Code Online (Sandbox Code Playgroud)
我定义了一个Sum()重载来操作这些值:
static class MoneyExtensions
{
public static Money Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, Money> selector)
{
return source.Select(x => (decimal)selector(x)).Sum();
}
}
Run Code Online (Sandbox Code Playgroud)
我没想到的是这种扩展方法会干扰现有的Sum()扩展方法:
var source = new[] { "2" };
Money thisWorks = source.Sum(x => Money.Parse(x));
int thisWorksToo = source.Sum(new Func<string, int>(x => int.Parse(x)));
int thisDoesNot = source.Sum(x => int.Parse(x));
Run Code Online (Sandbox Code Playgroud)
错误是"无法将类型'Money'隐式转换为'int'.存在显式转换(您是否错过了转换?)".编译器是否支持int => decimal => Money隐式转换而不是解决完全匹配的重载?
从C#4.0规范,第7.6.5.2节:
前面的规则意味着实例方法优先于扩展方法,内部命名空间声明中可用的扩展方法优先于外部命名空间声明中可用的扩展方法,并且直接在命名空间中声明的扩展方法优先于导入到该命名空间中的扩展方法.带有using namespace指令的命名空间
可能这会导致您的Money Sum扩展方法优先于Linq的方法 - 这就是为什么您没有得到"模糊方法调用"错误的原因.