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)
你看,我试着给彼此增加两点.它只是不起作用(这是预期的).我很乐意让这个工作.
有任何想法吗?
它不会按照你期望的方式发生.该唯一的过载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
方法,但我不相信增强可读性.
我阅读了文档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)
在同一文档我还看到一个显式转换Point
到Size
.因此,试试这个:
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)