积极答复者
实例化类,什么时候要用new,什么时候不用?

问题
-
Dim dirinfo As New System.IO.DirectoryInfo("c:\txt")
Dim file As System.IO.FileInfo如题,请教了。例如上面两条语句,第一条必须加new关键字,而第二条语句如果加了new关键字就会提示出错。真是糊涂了。
还有下面这两句:都是定义为XmlDocument,为什么一个要用new而另一个不用?急盼解决,小弟这厢有礼了.
1、 Dim doc As New XmlDocument
doc.LoadXml("<Menu></Menu>")2、Dim doc As XmlDocument = xmlNode.OwnerDocument
答案
-
DIM创建的引用类型的变量默认为null,可以在dim的时候就把变量的值设置为一个新建的变量的引用,也可以在dim之后再给变量赋值。
如果你在使用变量之前没有给变量赋值过,编译器会报告这个错误。
The following is signature, not part of post
Please mark the post answered your question as the answer, and mark other helpful posts as helpful.
Visual C++ MVP- 已标记为答案 feiyun0112Moderator 2010年5月24日 3:33
全部回复
-
DIM创建的引用类型的变量默认为null,可以在dim的时候就把变量的值设置为一个新建的变量的引用,也可以在dim之后再给变量赋值。
如果你在使用变量之前没有给变量赋值过,编译器会报告这个错误。
The following is signature, not part of post
Please mark the post answered your question as the answer, and mark other helpful posts as helpful.
Visual C++ MVP- 已标记为答案 feiyun0112Moderator 2010年5月24日 3:33
-
谢谢两位版主的解答。我就是用Dim file As System.IO.FileInfo初始化FileInfo的。没有任何问题。下面是我写的一个读取指定文件夹下文件的过程,调试没有问题。现在就是在什么时候用new关键字很迷惑了,非常想弄明白这个new到底时候用,啥时候又不能用?呵呵,两位版主费心了
比如说第3行的代码如果改成 “Dim file As new System.IO.FileInfo”,系统就会报错“说是file没有为public sub new(filename as string)的参数‘filename’指定参数”
第4行的代码如果改成“Dim files() As new System.IO.FileInfo = dirinfo.GetFiles”,系统就会报错“说是dirinfo.GetFiles应为结束语句”
1 Private Sub setlb(ByVal dir As String)
2 Dim dirinfo As New System.IO.DirectoryInfo(dir)
3 Dim file As System.IO.FileInfo
4 Dim files() As System.IO.FileInfo = dirinfo.GetFiles
5 If (files IsNot Nothing) Then
6 For Each file In files
7 lb.Items.Add(file.FullName)
8 Next
9 End If
10 End Sub