Difference between VB.Net and C# “As New WebControl”

后端 未结 4 411
情深已故
情深已故 2021-01-15 06:02

I was refactoring some code, and part of it included moving it from VB.Net to C#.

The old code declared a member like this:

Protected viewMode As New         


        
4条回答
  •  遥遥无期
    2021-01-15 06:37

    Accessing inherited protected constructors from a derived class in any context would raise data encapsulation issues.

    Historically, C# since very first version allowed such access. But it was fixed in VS 2005. Derived classes can call their base protected constructors only from their own constructor now.

    class Base
    {
        protected Base()
        {
        }
    }
    
    class Derived : Base
    {
        public Derived() : base() // Still allowed in VS 2005
        {
        }
    
        public void Main()
        {
            Base b = new Base(); // Allowed in VS 2003, but error in VS 2005
        }
    }
    

    In VB.NET, you can initialize variables in two ways. First with the assignment operator followed the declaration; second with the "As New" statement.

    In case of the protected constructor, the "As New" always works fine. As for initialization by assignment it will raise a compilation error. But if you have more than one constructor in the base class, the assignment initialization will work as well!

    Class Base
        Protected Sub New()
        End Sub
    End Class
    
    Class Derived
        Inherits Base
    
        Public Sub Main()
            Dim foo As New Base // Allowed
            Dim moo As Base = New Base() // Error if Base has only one constructor
        End Sub
    End Class
    

    Probably the reason why VB.NET allows this kind of access is in compatibility with legacy code.

    More details: http://blogs.msdn.com/b/peterhal/archive/2005/06/29/434070.aspx

提交回复
热议问题