What is allowed in Visual Basic that's prohibited in C# (or vice versa)?

后端 未结 21 1885
渐次进展
渐次进展 2020-12-05 06:07

This is code-related as in what the compiler will allow you to do in one language, but not allow you to do in another language (e.g. optional parameters in

21条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 06:22

    VB allows nonvirtual calls to virtual instance methods (call in IL), whereas C# only allows virtual calls (callvirt in IL). Consider the following code:

    Class Base
        Public Overridable Sub Foo()
            Console.WriteLine("Base")
        End Sub
    
        Public Sub InvokeFoo()
            Me.Foo()
            MyClass.Foo()
        End Sub
    End Class
    
    Class Derived : Inherits Base
        Public Overrides Sub Foo()
            Console.WriteLine("Derived")
        End Sub
    End Class
    
    Dim d As Base = New Derived()
    d.InvokeFoo()
    

    The output is:

    Derived
    Base
    

    That's not possible in C# (without resorting to Reflection.Emit).

提交回复
热议问题