声明时未实例化对象的原因是什么? [英] What is the reason for not instantiating an object at the time of declaration?

查看:30
本文介绍了声明时未实例化对象的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我不得不深入研究一些 VB6 代码,我到处都看到了这种模式:

I had to delve into some VB6 code recently and I saw this pattern all over the place:

dim o as obj
set o = new obj

为什么不是这个?

dim o as new obj

我记得 15 年前有一个很好的理由,但我现在不记得是什么了.有人记得吗?理由还成立吗?

I remember from 15 years ago that there was a good reason for this, but I can't remember what it was now. Anyone remember? Is the reason still valid?

推荐答案

可能还有其他原因,但在 VB6 中使用 New 关键字将对象变暗可能会导致意外结果,因为 VB 会实例化任何时候被引用的对象.

There may be other reasons but in VB6 using the New keyword when you Dim an object can cause unexpected results because VB will instantiate the object whenever it is referenced.

Dim objMyObject as New SomeObject

Set objMyObject = Nothing   ' the object is nothing

If objMyObject Is Nothing Then  ' referencing the object instantiates again
   MsgBox "My object is destroyed"  ' what you would probably expect
Else
   MsgBox "My object still exists"
End If

这篇关于声明时未实例化对象的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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