如何让+运算符在相互添加两个点的同时工作?

Tgy*_*gys 6 .net c# point operators winforms

有没有办法让+操作员为Point对象工作?

举个例子,这个小片段:

this.cm1.Show((MouseEventArgs)e.Location+this.i_rendered.Location);
Run Code Online (Sandbox Code Playgroud)

你看,我试着给彼此增加两点.它只是不起作用(这是预期的).我很乐意让这个工作.

有任何想法吗?

Cod*_*ray 7

它不会按照你期望的方式发生.该唯一的过载Point结构提供了用于+(加法)操作者是一个转换的坐标Point通过Size.

没有办法将两个Point结构加在一起,我甚至不确定这意味着什么.

考虑到你不能编写超载运算符的扩展方法,也不要浪费太多时间来计算它.

幸运的是,在编译语言中,将代码分成多行并不会受到惩罚.因此,您可以按如下方式重新编写代码:

Point newLocation = new Point(e.Location.X + this.i_rendered.Location.X,
                              e.Location.Y + this.i_rendered.Location.Y);
this.cm1.Show(newLocation);
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用该Offset方法,但我不相信增强可读性.


Jep*_*sen 6

我阅读了文档System.Drawing.Point(在Cody Gray的答案中链接),它有一个实例方法Offset.该方法改变了当前Point(设计者选择制作Point一个可变的结构!).

所以这是一个例子:

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

在同一文档我还看到一个显式转换PointSize.因此,试试这个:

var p1 = new Point(10, 20);
var p2 = new Point(6, 7);
Point pTotal = p1 + (Size)p2; // your solution?
Run Code Online (Sandbox Code Playgroud)