Objects implicitly instantiated in vb.net?

前端 未结 2 1783
耶瑟儿~
耶瑟儿~ 2020-12-03 22:20

I am maintaining an application that has both VB.NET and c# components. I thought these two languages differed only in syntax, but I have found a strange feature in VB.NET t

2条回答
  •  旧时难觅i
    2020-12-03 23:01

    For forms, VB creates a default instance for you behind the scenes. e.g., the following VB:

    Public Class bill_staff
        Inherits System.Windows.Forms.Form
    End Class
    
    class testclass
        sub testmethod()
            bill_staff.Show()
        end sub
    end class
    

    is equivalent to the following C#:

    public class bill_staff : System.Windows.Forms.Form
    {
    
        private static bill_staff _DefaultInstance;
        public static bill_staff DefaultInstance
        {
            get
            {
                if (_DefaultInstance == null)
                    _DefaultInstance = new bill_staff();
    
                return _DefaultInstance;
            }
        }
    }
    
    internal class testclass
    {
        public void testmethod()
        {
            bill_staff.DefaultInstance.Show();
        }
    }
    

    This only occurs in VB for forms (classes which inherit from System.Windows.Forms.Form). Personally, I think this is a terrible 'feature' of VB - it confuses the distinction between class and instance.

提交回复
热议问题