vb.net 的實現和C# 的實現有很多方面都不一樣,今天就拿 Overload 來做個對比。
大家可能都對 C# 比較熟悉,我列出一下一段代碼:
namespace OverloaddingCS
{
public class Test
{
public static void Main()
{
Derived d=new Derived();
d.WriteLine(10);
d.WriteLine("11");
d.WriteLine(10.5);
}
}
class Base
{
public void WriteLine(String AnyString)
{
Console.WriteLine(AnyString + " called Base:String") ;
}
public void WriteLine(int AnyInteger)
{
Console.WriteLine(AnyInteger.ToString() + " called Base:Integer");
}
}
class Derived : Base
{
public void WriteLine(double AnyDouble)
{
Console.WriteLine(AnyDouble.ToString() + " called Derived:double");
}
}
}
答案很簡單,如果你對c++ 比較熟悉的話
10 called Derived:double
11 called Base:String
10.5 called Derived:double
如果我把類似的代碼翻譯成 vb.net ,注意是原本的翻譯
Class TestClass Test
Public Shared Sub Main()Sub Main()
Dim objMyTest As New Derived
With objMyTest
.WriteLine(10)
.WriteLine("11")
.WriteLine(10.5)
End With
Console.ReadLine()
End Sub
End Class
Class BaseClass Base
Public Sub WriteLine()Sub WriteLine(ByVal AnyString As String)
Console.WriteLine(AnyString + " called Base:String")
End Sub
Public Sub WriteLine()Sub WriteLine(ByVal AnyInteger As Integer)
Console.WriteLine(AnyInteger.ToString + " called Base:Integer")
End Sub
End Class
Class DerivedClass Derived : Inherits Base
Public Overloads Sub WriteLine()Sub WriteLine(ByVal AnyDouble As Double)
Console.WriteLine(AnyDouble.ToString + " called Derived:Double")
End Sub
End Class
代碼起始是一樣的。我直接公布結果,起始跟 C# 的結果不一樣
10 called Base:Integer
11 called Base:String
10.5 called Derived:Double
結果出乎意料,起始也是情理之中的事情。
我就不做解釋了,關鍵是提醒各位有 C++ 專項 VB.NET 的時候,不要想當然的以為 VB.NET 的處理方式跟 C# 一樣。