如何在不选择大小写的情况下选择要实例化的对象?

时间:2018-08-01 21:23:06

标签: vb.net class inheritance

说我有三节课。基本类 Person 和其他两个类( Employee Manager )均继承自 Person

Public Class Person
  Public Property Name As String
  Public Overridable ReadOnly Property Salary As Decimal
    Get
     Return 0
    End Get
  End Property

  Public Sub New()
  End Sub
  End Class

班级员工

Public Class Employee
Inherits Person
Overrides ReadOnly Property Salary As Decimal
  Get
   Return 100
  End Get
End Property

Sub New()
MyBase.New()
End Sub
End Class

课程经理

Public Class Manager
Inherits Person

Overrides ReadOnly Property Salary As Decimal
    Get
        Return 1000
    End Get
End Property
Sub New()
    MyBase.New()
End Sub
End Class

我的问题是如何创建一个新的(基于 ListBox ),该人可以是 / Employee < / strong>或 Manager ,并在不通过ListBox1_SelectedIndexChanged事件中的Select Case或If-else的情况下检索Salary属性。为了进行选择,我添加了另一个名为 Identify 的类,该类采用列表框的选定索引,并将其传递给 getProsonType 方法并返回选定的类别。请在下面查看我的代码。

form1代码如下:

Public Class Form1
Private P As Identify

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles 
MyBase.Load
    ListBox1.Items.Add("Person")
    ListBox1.Items.Add("Employee")
    ListBox1.Items.Add("Manager")
End Sub

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As 
EventArgs) Handles ListBox1.SelectedIndexChanged
    P = New Identify(CType(ListBox1.SelectedIndex, PersonType))
    Dim PGeneral As Person
    PGeneral = P.GeneralPerson
    Label1.Text = PGeneral.Salary
 End Sub
End Class

我已将这三种类型分配给公共枚举 PersonType ,只是为了限制选择。

Public Enum PersonType
  Person = 0
  Employee = 1
  Manager = 2
End Enum

身份类如下:

Public Class Identify
 Public Property PType As PersonType
 Public ReadOnly Property GeneralPerson As Person
    Get
        Return getProsonType(PType)
    End Get
 End Property

 Private Function getProsonType(ByVal SomeOne As PersonType) As Person
    Dim pp As Person

    Select Case SomeOne
        Case PersonType.Person
            pp = New Person()
        Case PersonType.Employee
            pp = New Employee()
        Case PersonType.Manager
            pp = New Manager()
    End Select
    Return GeneralPerson
   End Function

  Sub New(ByVal PersonType As PersonType)
    Me.PType = PersonType
  End Sub
 End Class

运行项目后,出现错误 System.StackOverflowException 。我不确定这是最干净的方法还是正确的方法,因此我在许多地方查看并达到了死胡同! 请帮助我纠正此问题或找到更好的方法。 预先感谢。

0 个答案:

没有答案