比較此C#(fiddle)爲什麼VB編譯器在C#中無法捕獲到接口類型的無效隱式轉換?
public class Program
{
public static void Main()
{
IFoo test;
test = new Impl();
test = new NoImpl();
}
}
public interface IFoo {}
public class NoImpl {}
public class Impl : IFoo {}
此VB(fiddle)。
Public Module Module1
Public Sub Main()
Dim test as IFoo
test = new Impl()
test = new NoImpl()
End Sub
End Module
Public Interface IFoo
End Interface
Public Class NoImpl
End Class
Public Class Impl
Implements IFoo
End Class
在C#中,編譯器將NoImpl的隱式強制轉換爲錯誤。在VB中,代碼編譯但在運行時失敗。
這兩種語言/編譯器之間有什麼特別的區別?
可能與Why no compiler error when I cast a class to an interface it doesn't implement?
是否在VB編譯器中嚴格打開選項? –
@RonBeyer不,它不是;只需將它添加到[小提琴](https://dotnetfiddle.net/fxgMK3),它不再編譯 – Sehnsucht
當我是一個VB程序員(時代.NET 1.1)時,我宗教上確保選項嚴格和選項明確被打開,否則這些類型的錯誤將永遠不會彈出,直到運行時。 –