简体   繁体   中英

How do i set a default property for this variable?

The Loc variable is underlined and says it cannot be indexed because it has no default property. Can I set a default property or is there something else I can and should do?

    Private Sub tmrLeft_Tick(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles tmrLeft.Tick
    Dim MoveSpeed As Integer = 10
    Dim Loc As Point
    If Not picPlayer.Location.X - MoveSpeed < 0 Then
        Loc = New Point(picPlayer.Location.X - MoveSpeed, picPlayer.Location.Y)
        picPlayer.Location = Loc()
    End If
End Sub

The problem is that you have some unnecessary parentheses. You need to change this line:

picPlayer.Location = Loc()

to this:

picPlayer.Location = Loc

Parentheses can be a little confusing in VB, since they can be used for either a method invocation or a list item index. In this context, Loc is a variable, not a method, so when you put the parentheses after it, the compiler assumes that you must be attempting to access a particular item of a list by index. But, since Loc is not an array, and it's not a list with a default index-accessible property (like List.Item , where it's the default indexer, so myList.Item(3) means the same thing as myList(3) ). So, it gives an error saying that Loc can't be indexed.

In programming (VBA in this case), parentheses are included when you reference a method:

This is variable

Dim Loc As Point

Dim NewPoint = Loc

This is a method

  'Function to Add Two Numbers and Then Subtract a Third Number Function SumMinus(dNum1 As Double, dNum2 As Double, dNum3 As Double) As Double SumMinus = dNum1 + dNum2 - dNum3 End Function 

Dim Result As Double

Result = SumMinus(..., ..., ...);

As you see, the parentheses give it a different meaning.

variable

method()


Private Sub tmrLeft_Tick(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles tmrLeft.Tick
        Dim MoveSpeed As Integer = 10
        Dim Loc As Point
        If Not picPlayer.Location.X - MoveSpeed < 0 Then
            Loc = New Point(picPlayer.Location.X - MoveSpeed, picPlayer.Location.Y)
            picPlayer.Location = Loc // Without parenthesis
        End If
    End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM