gpt4 book ai didi

c# - 隐式强制转换对委托(delegate)类型推断的意外影响

转载 作者:太空狗 更新时间:2023-10-29 17:49:52 25 4
gpt4 key购买 nike

我有一个简单的 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);
}
}

然后我定义了一个 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();
}
}

我没想到的是这个扩展方法会干扰现有的 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));

错误是“无法将类型‘Money’隐式转换为‘int’。存在显式转换(是否缺少强制转换?)”。编译器支持 int => decimal => Money 隐式转换而不是解析完全匹配的重载是否正确?

最佳答案

来自 C# 4.0 规范,第 7.6.5.2 节:

The preceding rules mean that instance methods take precedence over extension methods, that extension methods available in inner namespace declarations take precedence over extension methods available in outer namespace declarations, and that extension methods declared directly in a namespace take precedence over extension methods imported into that same namespace with a using namespace directive

这可能导致您的 Money Sum 扩展方法优先于 Linq 中的扩展方法 - 这就是为什么您没有收到“模糊方法调用”错误的原因。

关于c# - 隐式强制转换对委托(delegate)类型推断的意外影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6534553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com