Dim
pt
As
New
Point(
0
,
0
)
pt += New Size( 10 , 10 )
pt += New Size( 10 , 10 )
C# 中没有问题。在 VB.NET 中就不能编译,错误是
Operator '+' is not defined for types 'System.Drawing.Point' and 'System.Drawing.Size'.
其实看一下 Point 的il 代码,已经有了一个加法的重载
.method
public
hidebysig specialname
static
valuetype System.Drawing.Point op_Addition(valuetype System.Drawing.Point pt,
valuetype System.Drawing.Size sz) cil managed
{
// Code size 36 (0x24)
.maxstack 8
IL_0000: ldarga.s pt
IL_0002: call instance int32 System.Drawing.Point::get_X()
IL_0007: ldarga.s sz
IL_0009: call instance int32 System.Drawing.Size::get_Width()
IL_000e: add
IL_000f: ldarga.s pt
IL_0011: call instance int32 System.Drawing.Point::get_Y()
IL_0016: ldarga.s sz
IL_0018: call instance int32 System.Drawing.Size::get_Height()
IL_001d: add
IL_001e: newobj instance void System.Drawing.Point::.ctor(int32,
int32)
IL_0023: ret
} // end of method Point::op_Addition
valuetype System.Drawing.Point op_Addition(valuetype System.Drawing.Point pt,
valuetype System.Drawing.Size sz) cil managed
{
// Code size 36 (0x24)
.maxstack 8
IL_0000: ldarga.s pt
IL_0002: call instance int32 System.Drawing.Point::get_X()
IL_0007: ldarga.s sz
IL_0009: call instance int32 System.Drawing.Size::get_Width()
IL_000e: add
IL_000f: ldarga.s pt
IL_0011: call instance int32 System.Drawing.Point::get_Y()
IL_0016: ldarga.s sz
IL_0018: call instance int32 System.Drawing.Size::get_Height()
IL_001d: add
IL_001e: newobj instance void System.Drawing.Point::.ctor(int32,
int32)
IL_0023: ret
} // end of method Point::op_Addition
无奈只好改成:
Dim
pt
As
New
Point(
0
,
0
)
pt = Point.op_Addition(pt, New Size( 10 , 10 ))
pt = Point.op_Addition(pt, New Size( 10 , 10 ))
查了一下,msdn mag 最新的一期提到了这个问题,其实原因很简单,vb.net 的compiler 还没有100% 对运算符重载支持的足够好。
原文地址:http://www.msdn.microsoft.com/msdnmag/issues/04/12/AdvancedBasics/default.aspx