Why is there a default instance of every form in VB.Net but not in C#?

前端 未结 2 1069
小蘑菇
小蘑菇 2020-11-22 02:55

I\'m just curious to know that there is the (Name) property, which represents the name of the Form class. This property is used within the namespace to uniquely identify the

2条回答
  •  失恋的感觉
    2020-11-22 03:42

    VB is adding a load of code into your project behind your back, basically.

    The easiest way to see what's going on is to build a minimal project and look at it with Reflector. I've just created a new WinForms app with VB and added this class:

    Public Class OtherClass    
        Public Sub Foo()
            Form1.Show()
        End Sub
    End Class
    

    The compiled code for Foo looks like this when decompiled as C#:

    public void Foo()
    {
        MyProject.Forms.Form1.Show();
    }
    

    MyProject.Forms is a property in the generated MyProject class, of type MyForms. When you start diving into this you see quite large amounts of generated code in there.

    C# could do all of this, of course - but it doesn't typically have a history of doing quite as much behind your back. It builds extra methods and types for things like anonymous types, iterator blocks, lambda expressions etc - but not in quite the same way that VB does here. All the code that C# builds corresponds to source code that you've written - just cleverly transformed.

    There are arguments for both approaches, of course. Personally I prefer the C# approach, but that's probably no surprise. I don't see why there should be a way of accessing an instance of a form as if it was a singleton but only for forms... I like the language to work the same way whether I'm using GUI classes or anything else, basically.

提交回复
热议问题