System.Math.Round调用一类正常另一类歧义,是否为VS2022问题?
Math.Round调用歧义问题解析
问题场景
- 在
Workspace类中调用Math.Round完全正常:
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Shapes; namespace Editor.View.Controls { public partial class Workspace : UserControl { public Workspace() => InitializeComponent(); // ... 其他方法 public Point RoundPoint(Point p, int r) { return new Point(Math.Round(p.X / r) * r, Math.Round(p.Y / r) * r); } } }
- 但将
RoundPoint方法移至UiHelpers类后,出现编译错误:
using System; using System.Drawing; namespace Editor.View.Controls { public static class UiHelpers { public static Point RoundPoint(Point p, int r) { return new Point(Math.Round(p.X / r) * r, Math.Round(p.Y / r) * r); } } // ... }
错误信息:
Error CS0121 调用在以下方法或属性之间不明确:
'Math.Round(decimal)' 和
'Math.Round(double)' Editor\View\Controls\UiHelpers.cs
问题原因
核心是两个类引用的Point类型完全不同:
Workspace类用的是System.Windows.Point,它的X、Y属性是double类型。计算p.X / r时,double除以int结果仍为double,Math.Round会明确匹配Math.Round(double)重载,没有歧义。UiHelpers类用的是System.Drawing.Point,它的X、Y属性是int类型。p.X / r是int除以int,结果为int。但Math.Round没有直接接收int的重载,int可以隐式转换为decimal或double,编译器无法判断该调用哪个重载,因此抛出歧义错误。
解决办法
有两种实用处理方式:
- 明确指定转换类型,让编译器确定匹配的重载:
// 转换为double类型,匹配Math.Round(double) return new Point((int)Math.Round((double)p.X / r) * r, (int)Math.Round((double)p.Y / r) * r); // 或者转换为decimal类型,匹配Math.Round(decimal) return new Point((int)Math.Round((decimal)p.X / r) * r, (int)Math.Round((decimal)p.Y / r) * r); - 统一
Point类型引用:如果是WPF项目,建议给UiHelpers类改用System.Windows.Point,移除using System.Drawing;并添加using System.Windows;,和原代码逻辑保持一致,无需额外类型转换。
内容的提问来源于stack exchange,提问作者Kamil
相关产品推荐
相关产品推荐

