在 vb.net 中隐式实例化的对象? [英] Objects implicitly instantiated in vb.net?

查看:28
本文介绍了在 vb.net 中隐式实例化的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在维护一个具有 VB.NET 和 c# 组件的应用程序.我以为这两种语言只是在语法上有所不同,但我发现 VB.NET 中有一个 C# 中没有的奇怪功能.

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 that is not present in C#.

在 VB.NET 中,我有以下类:

In VB.NET, I have the following class:

Public Class bill_staff Inherits System.Windows.Forms.Form
    ....
End Class

如果我想在 C# 中使用这个类,我这样做:

If I want to use this class in C#, I do this:

using (var frm = new bill_staff())
    frm.ShowDialog();

但是,在 VB.NET 代码中,可以这样使用该类:

However, in the VB.NET code, the class can be used like this:

bill_staff.ShowDialog();

ShowDialog 在元数据中定义如下:

ShowDialog is defined in the metadata like this:

Public Function ShowDialog() As System.Windows.Forms.DialogResult

所以在 VB.NET 中,可以在类上调用实例方法.据我所知,这似乎隐式地创建了该类的一个新实例,然后在该对象上调用该方法.在 C# 中,这是不可能的 - 必须在类上调用静态方法,并且必须在对象上调用实例方法.

So in VB.NET, it is possible to call an instance method on the class. As far as I can tell, this seems to implicitly create a new instance of the class, and then calls the method on that object. In C#, this is not possible - static methods must be called on the class, and instance methods must be called on objects.

我在 Internet 上找不到有关此的任何信息.这个功能叫什么,它是个好习惯吗?

I can't find any information about this on the Internet. What is the feature called, and is it good practice?

该项目最初是从 VB6 转换而来的 - 这是一些奇怪的遗留功能吗?

The project was initially converted from VB6 - is it some weird legacy feature?

推荐答案

是的,这是遗留行为.类直到 v4 才出现在 VB 中,在那之前 Form1.Show 是显示表单的方式.为了保持之前的代码兼容(VB3也很流行),旧方法被保留.

Yes that is legacy behavior. Classes did not show up in VB until v4, before that Form1.Show was The Way to show forms. In order to keep previous code compatible (VB3 was also very popular), the old method was maintained.

.NET 仍然支持它作为显示表单的合法方式.最初,添加它是为了便于将 VB6 代码迁移到 VB.NET.但是否也可以使在 VB 中运行某些东西变得容易——MS 将其称为触手可及的功能和类似的短语.

It is still supported in .NET as a legal means to show forms. Initially, this was added to make it easy to migrate VB6 code to VB.NET. But is also there to make it easy to get something running in VB - MS refers to it as functionality at your fingertips and similar phrases.

基本上,它为修补程序提供了一种无需理解对象和 OOP 即可轻松编程的方法.想象一下,如果 Form1.Show 抛出错误,我们会有什么问题.

Basically, it provides the tinkerer an easy way to program without understanding Objects and OOP. Imagine the questions we would have here if Form1.Show threw an error.

显式实例化是更好的方法,因为它是面向对象的,并且当您真正想要使用现有实例时,它不太可能使您的代码引用或创建新的 Form2.

Explicit instancing is the better method because it is object oriented and makes it less likely your code will reference - or create - a new Form2 when you actually wanted to use an existing instance.

这篇关于在 vb.net 中隐式实例化的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆