访问“发件人”而不传递参数

时间:2015-11-27 14:21:40

标签: vb.net

我有一个Main类,其中我有一个Tomato对象的填充数组(现在显示在这个例子中)。我想访问特定的Tomato并使用LowerPrice子例程而不传递发件人对象。

Public Class Main
   Dim TomatoArray() As Tomato

   Private Sub HaveATomatoSale
      'This is how I want to do my price reduction
      TomatoArray(0).LowerPrice(10)
      'This is NOT how I want to do my price reduction, i.e. including a sender object
      TomatoArray(0).LowerPrice(TomatoArray(0), 10)
   End Sub       
End Class

我在Tomato类中也有一个函数,如下所示:

Public Class tomato
   Dim tomato_price As Integer = 15

   Public Property Price As Integer
      Get
         Return tomato_price
      End Get
      Set(value As Integer)
         tomato_price = value
      End Set
   End Property

   Public Sub LowerPrice(ByVal Decrease As Integer)
      'What should I point to here?
      sender.tomato_price -= Decrease
   End Sub
End Class

我搜索了SO,MSDN和互联网的其余部分,以便对这个看似简单的问题进行简单的回答,但无济于事(可能是因为我缺少一个好的关键字!)。我怎样才能做到这一点?谢谢!

1 个答案:

答案 0 :(得分:2)

您要查找的关键字是Me

Public Sub LowerPrice(ByVal Decrease As Integer)
    Me.tomato_price -= Decrease
End Sub

请注意Me是可选的,因此以下内容也可以使用:

Public Sub LowerPrice(ByVal Decrease As Integer)
    tomato_price -= Decrease
End Sub

实际上,您可能希望利用自动属性并将代码缩减为:

Public Class tomato
   Public Property Price As Integer = 15

   Public Sub LowerPrice(ByVal decreaseBy As Integer)
      Me.Price -= decreaseBy
   End Sub
End Class