我需要将PointF与Point进行比较,如下所示:
PointF myPointF = new PointF(1.1,1.1);
Point myPoint = new Point(1,1);
bool Equal = (myPointF == myPoint);
但我想知道下列哪一项是正确的,或者如果比较真的发生了不同的事情:
可以写一个测试,但我希望在文档中看到答案。
另外,there exists an implicit conversion from Point to PointF而不是相反,所以我认为足以说Point正在转换为PointF,但我再也不知道了。
答案 0 :(得分:4)
使用LinqPad,很容易看到IL,看看发生了什么。基本上,Point
转换为PointF
,然后为==
调用PointF
相等方法。
例如,使用此代码:
System.Drawing.PointF myPointF = new System.Drawing.PointF(1.1f ,1.1f);
System.Drawing.Point myPoint = new System.Drawing.Point(1,1);
bool equal = (myPointF == myPoint);
Console.WriteLine(equal);
生成以下IL:
IL_0001: ldloca.s 00 // myPointF
IL_0003: ldc.r4 CD CC 8C 3F
IL_0008: ldc.r4 CD CC 8C 3F
IL_000D: call System.Drawing.PointF..ctor
IL_0012: nop
IL_0013: ldloca.s 01 // myPoint
IL_0015: ldc.i4.1
IL_0016: ldc.i4.1
IL_0017: call System.Drawing.Point..ctor
IL_001C: nop
IL_001D: ldloc.0 // myPointF
IL_001E: ldloc.1 // myPoint
IL_001F: call System.Drawing.Point.op_Implicit //<- convert Point to PointF
IL_0024: call System.Drawing.PointF.op_Equality //<- PointF equality
IL_0029: stloc.2 // equal
IL_002A: ldloc.2 // equal
IL_002B: call System.Console.WriteLine
如果您使用ILSpy,则可以找到Point.op_Implicit
和PointF.op_Equality
的内容。
// System.Drawing.Point
public static implicit operator PointF(Point p)
{
return new PointF((float)p.X, (float)p.Y);
}
// System.Drawing.PointF
public static bool operator ==(PointF left, PointF right)
{
return left.X == right.X && left.Y == right.Y;
}
这表明当int
转换为float
时,Point
值会转换为PointF
值,然后float
值转换为PointF
原始PointF
实例与转换后的{{1}}实例进行比较。
答案 1 :(得分:3)
让我们看看ildasm.exe显示的内容:
IL_001f: call valuetype [System.Drawing]System.Drawing.PointF [System.Drawing]System.Drawing.Point::op_Implicit(valuetype [System.Drawing]System.Drawing.Point)
IL_0024: call bool [System.Drawing]System.Drawing.PointF::op_Equality(valuetype [System.Drawing]System.Drawing.PointF,valuetype [System.Drawing]System.Drawing.PointF)
所以,是的。 Point被视为PointF进行比较。