比较这个 C# ( fiddle )
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? 有关
最佳答案
来自 this page关于Option Strict
:
By default, the Visual Basic .NET or Visual Basic compiler does not enforce strict data typing. ... In Visual Basic .NET, you can typically convert any data type to any other data type implicitly.
所以这里发生的是 VB 编译器的“松散”性质,它允许在运行时失败的事情通过。 C# 在类型转换方面并不那么宽松,这就是为什么它总是给出编译器错误,而 VB 则不会。使用 Option Strict
有助于在编译时而非运行时识别这些错误。
如果不使用 Option Strict
,VB 将允许任何类型的转换/强制转换顺利进行,但缩小转换、精度损失转换和完全无效的转换会出现运行-时间错误。顶部发布的链接包含有关哪些类型转换被视为扩大的信息。
关于c# - 为什么 VB 编译器不能捕获对接口(interface)类型的无效隐式转换,而 C# 可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33570225/