VB NET面向对象

时间:2015-10-12 22:42:14

标签: vb.net oop

我对VB.NET上的课程(以及一般的整个OOP概念)有点新意,所以很抱歉提前做了不好的解释。 我创建了一个类似的类:

Public Class MyApp

private var1 as integer = 2

Private Function getProfile(id As Integer)
    'Imaginary server request according to ID
    'Following that was received:
    Dim name As String = "John"
    Dim age As integer = 30
End Function

End Class

我希望能够通过使用myApp.getProfile调用getProfile,这是我可以处理的。 我无法管理的只显示年龄或姓名。 像这样:

MyApp.getProfile(4341).age

我怎样才能实现这样的目标?就像在函数中使用子函数一样。

1 个答案:

答案 0 :(得分:2)

要以这种方式调用方法,它需要是静态的(标记为Shared)和公共。要使其返回名称和年龄作为属性,您需要具有这些属性的类。例如:

Public Class MyApp

  Public Shared Function GetProfile(id As Integer)
    Dim name As String = "John"
    Dim age As integer = 30
    return New ServerResult(name, age)
  End Function

End Class

Public Class ServerResult

  Public Name as String
  Public Age as Integer

  Public Sub New(n as String, a as Integer)
    Name = n
    age = a
  End Sub

End Class

用法示例:

Dim age as Integer = MyApp.GetProfile(42).Age

另:

Dim result As ServerResult = MyApp.GetProfile(1337)
Dim info As String = String.Format("{0}, {1}", result.Name, result.Age)

注意:使方法静态取决于您想要如何调用它。您可能想要创建MyApp类的实例,并且有一个非静态的方法。