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

后端 未结 21 1879
渐次进展
渐次进展 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:28

    In VB you can implement an interface with a method of any name - i.e. a method "Class.A" can implement interface method "Interface.B".

    In C#, you would have to introduce an extra level of indirection to achieve this - an explicit interface implementation that calls "Class.A".

    This is mainly noticeable when you want "Class.A" to be protected and/or virtual (explicit interface implementations are neither); if it was just "private" you'd probably just leave it as the explicit interface implementation.

    C#:

    interface IFoo {
        void B();
    }
    class Foo : IFoo { 
        void IFoo.B() {A();} // <====  extra method here
        protected virtual void A() {}
    }
    

    VB:

    Interface IFoo
        Sub B()
    End Interface
    Class Foo
        Implements IFoo
        Protected Overridable Sub A() Implements IFoo.B
        End Sub
    End Class
    

    In the IL, VB does this mapping directly (which is fine; it is not necessary for an implementing method to share a name).

提交回复
热议问题