简体   繁体   English

如果它不是静态方法,为什么我可以调用Form.Close()

[英]Why can I call Form.Close() if it's not a static method

Can someone explain this to me? 谁可以给我解释一下这个?

In Visual Studio 2010, create a VB.net Windows Forms App. 在Visual Studio 2010中,创建一个VB.net Windows窗体应用程序。 Add 2 forms: Form1 and Form2. 添加2个表单:Form1和Form2。 In the Form1 Load event type Form2.Close(). 在Form1 Load事件中键入Form2.Close()。 Now if we look in the method definition Close() is not a static (shared) method. 现在,如果我们查看方法定义,Close()不是静态(共享)方法。 So how is this possible to compile or to work at run time. 那么如何在运行时编译或工作呢?

Furthermore, do the same thing in C# and Form2.Close(); 此外,在C#和Form2.Close()中做同样的事情; doesn't compile. 不编译。

What's going on? 这是怎么回事? Why is this possible in VB.net and what is actually happening when that line of code is executed? 为什么在VB.net中可以实现这一点以及在执行该行代码时实际发生了什么?

You've discovered a VB.NET-ism called "default instance". 您已经发现了一个名为“默认实例”的VB.NET-ism。

The compiler is actually emitting this: 编译器实际发出这样的:

My.Forms.Form2.Close();

There is a nice writeup of that feature here : 这里有一个很好的特写

The default instance is an object of that type that the VB application framework creates and manages for you. 默认实例是VB应用程序框架为您创建和管理的该类型的对象。

... ...

If you use the default instance then you don't need to invoke a constructor explicitly. 如果使用默认实例,则无需显式调用构造函数。 You simply access the default instance directly via the My.Forms object 您只需通过My.Forms对象直接访问默认实例

The reason is that VB creates an automatic instance of the form if you just reference them by name, which could lead to unintended consequences at runtime if it isn't caught. 原因是如果您只是按名称引用它们,VB会创建表单的自动实例,如果没有捕获它,可能会在运行时导致意外后果。

There is no setting that I have found to prevent this from happening. 我发现没有任何设置可以防止这种情况发生。

However, you can "break" this behavior at compile time by changing the scope of the default constructor from Public to Friend or by removing the default constructor and adding one that requires a parameter. 但是,您可以通过将默认构造函数的范围从Public更改为Friend,或者通过删除默认构造函数并添加需要参数的构造函数来在编译时“中断”此行为。 Either or these changes will disable the automatic form references. 这些或这些更改将禁用自动表单引用。

You are correct, you cannot call Form2.Close(); 你是对的,你不能调用Form2.Close(); when Form2 is only a class type. Form2只是一个类类型。 VB.NET, however, creates a property with the same name behind the scenes, and so you are really calling Close on an instance of Form2 . 但是,VB.NET在幕后创建了一个具有相同名称的属性,因此您实际上是在Form2的实例上调用Close You can do the same in C#, if you manually create such a property. 如果手动创建此类属性,则可以在C#中执行相同操作。 It looks like a static method call, but it isn't. 它看起来像一个静态方法调用,但事实并非如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM