将用户输入传递给新的类实例

时间:2015-06-02 00:08:02

标签: vb.net class

好吧,我在这里浏览了20页,找不到我要找的东西......我在C#和其他语言中看过它......但不是Visual Basic ..

说我有课:

Public Class Cars
    Private doors as integer
    Private Liters as double
    Private otherStuff as string

 ' more code'
end class

假设我还有一个Form ..一个inputForm我们称之为有多个文本框供用户输入这些特性。第一个文本框标记为nameTextBox。有没有办法将该文本框的字符串值指定为新车?

喜欢的东西..

dim nameTextBox.value as new car

...

1 个答案:

答案 0 :(得分:3)

您班级中的字段是私有的,因此它们没有多大用处 - 没有其他代码能够看到这些值。

Public Class Car
    Public Property Make As String
    Public Property Model As String
    Public Property Year As Integer

    ' something the class may use/need but doesnt expose
    Private DealerCost As Decimal 

    ' the constructor - called when you create a NEW car
    Public Sub New(mk As String, md As String)
        Make = mk
        Model = md
    End Sub
    ...
End Class

通过仅指定采用参数的构造函数,我说如果不指定这些属性就无法创建新车。如果构造函数没有参数,那么你可以创建一个"空"汽车对象并单独设置每个属性。您可以同时执行这两项操作 - 称为重载 - 这样您就可以在开始时使用或不使用Make和Model创建汽车。

作为公共属性,其他代码可以检查它们以查看它是什么类型的汽车。

Dim myCar = New Car("Toyata", "Corolla")
myCar.Year = 2013
myCar.Color = Color.Blue

当然使用的文字可以来自用户输入:

Dim myCar = New Car(tbMake.Text, tbModel.Text)
Dim yr As Int32
If Integer.TryParse(tbYear.Text, yr) Then
    myCar.Year = yr
Else
     ' ToDo: scold user
End If