c# - 为什么 VB 编译器不能捕获对接口(interface)类型的无效隐式转换,而 C# 可以?

标签 c# vb.net compiler-errors

比较这个 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/

相关文章:

c++ - Visual C++ Studio 2010 无故显示生成错误

vba - 无法在 VBA 中使用我的简单 VB 类库

java - ArrayList运行时错误

c# - 用于生成显示 x 秒的初始屏幕的最小独立 WPF/C#

c# - 反编译的 DLL - 有助于判断它是 C# 还是 VB.NET 的线索?

.net - 柯里化(Currying)委托(delegate)参数的最佳模式是什么(使用 .NET 2.0 或更高版本)?

.net - 页面.Response.Write()

c - 错误: Disallowed system call: SYS_socketcall in C

Asp.NET Core 中的 c# AllowAutoRedirect 等价物

c# - 如何在 C# crystal reports visual studio 2010 中进行打印预览