vb.net 如何在 Visual Basic 中实现类构造函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3279106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement class constructor in Visual Basic?
提问by yonan2236
I just would like to know how to implement class constructor in this language.
我只想知道如何用这种语言实现类构造函数。
回答by Hans Olsson
Not sure what you mean with "class constructor" but I'd assume you mean one of the ones below.
不确定您对“类构造函数”的意思,但我认为您指的是以下其中之一。
Instance constructor:
实例构造函数:
Public Sub New()
End Sub
Shared constructor:
共享构造函数:
Shared Sub New()
End Sub
回答by ShieldOfSalvation
Suppose your class is called MyStudent. Here's how you define your class constructor:
假设您的班级名为 MyStudent。以下是定义类构造函数的方法:
Public Class MyStudent
Public StudentId As Integer
'Here's the class constructor:
Public Sub New(newStudentId As Integer)
StudentId = newStudentId
End Sub
End Class
Here's how you call it:
这是你如何称呼它的:
Dim student As New MyStudent(studentId)
Dim student As New MyStudent(studentId)
Of course, your class constructor can contain as many or as few arguments as you need--even none, in which case you leave the parentheses empty. You can also have several constructors for the same class, all with different combinations of arguments. These are known as different "signatures" for your class constructor.
当然,您的类构造函数可以包含您需要的任意数量或任意数量的参数——甚至没有,在这种情况下,您可以将括号留空。您还可以为同一个类使用多个构造函数,所有构造函数都具有不同的参数组合。这些被称为类构造函数的不同“签名”。
回答by Jonathan Allen
If you mean VB 6, that would be Private Sub Class_Initialize()
.
如果您的意思是 VB 6,那就是Private Sub Class_Initialize()
.
http://msdn.microsoft.com/en-us/library/55yzhfb2(VS.80).aspx
http://msdn.microsoft.com/en-us/library/55yzhfb2(VS.80).aspx
If you mean VB.NET it is Public Sub New()
or Shared Sub New()
.
如果您的意思是 VB.NET,则它是Public Sub New()
或Shared Sub New()
.
回答by Ankit Singh
A class with a field:
带有字段的类:
Public Class MyStudent
Public StudentId As Integer
The constructor:
构造函数:
Public Sub New(newStudentId As Integer)
StudentId = newStudentId
End Sub
End Class