如何使+运算符同时添加两个点?

问题描述 投票:6回答:3

是否有任何方法可以使+运算符适用于Point对象?

例如,以这个小片段为例:

this.cm1.Show((MouseEventArgs)e.Location+this.i_rendered.Location);

[您知道,我尝试将两个点互相添加。它只是不起作用(这是预期的)。我很想让这个工作正常。

有什么想法吗?

c# .net winforms operators point
3个回答
7
投票

这不会像您期望的那样发生。 Point结构提供给+(加法)运算符的唯一重载是one that translates the coordinates of the Point by a Size

无法将两个Point结构加在一起,我什至不知道那是什么意思。

考虑到Size,也不要浪费太多时间来弄清楚它。

幸运的是,在编译语言中,将代码分成多行没有任何惩罚。因此,您可以按以下方式重新编写代码:

Point

或者,您可以使用you cannot write extension methods that overload operators,但我不认为这可以提高可读性。


7
投票

我阅读了Point newLocation = new Point(e.Location.X + this.i_rendered.Location.X, e.Location.Y + this.i_rendered.Location.Y); this.cm1.Show(newLocation); 的文档(链接至Cody Gray的答案),它具有实例方法Offset method。该方法会改变当前的Offset(设计人员选择使System.Drawing.Point为可变结构!)。

所以这是一个例子:

Offset

在同一文档中,我还看到了从PointPoint的显式转换。因此,请尝试以下操作:

var p1 = new Point(10, 20);
var p2 = new Point(6, 7);
p1.Offset(p2); // will change p1 into the sum!

0
投票

最简单(也最干净)的解决方案是将i_rendered.Location转换为Size

Point

当简单的强制转换按照OP要求的方式完成工作时,我不知道如何或为什么需要将任何东西分解为复杂的X和Y分量。

© www.soinside.com 2019 - 2024. All rights reserved.