Domanda

I've recently started working with C# after working with VB.Net for a while.

In VB.Net you can raise an event with parameters that you pass in. For example

Event TileMoved(ThisTile As Tile)

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    RaiseEvent TileMoved(Me)
End Sub

Please could someone explain how to do this in C#?

Any help would be much appreciated.

È stato utile?

Soluzione

vb -> c# conversion gives this result.

public event TileMovedEventHandler TileMoved;
public delegate void TileMovedEventHandler(Tile ThisTile);

private void Button1_Click(System.Object sender, System.EventArgs e)
{
    if (TileMoved != null) {
        TileMoved(this);
    }
}

Altri suggerimenti

You can use an event data class. See here:

http://msdn.microsoft.com/en-us/library/edzehd2t(v=vs.110).aspx

You can think of events as a method call at an unpredictable time. The rest of the program doesn't really know when something will happen, so methods are 'delegated' to respond to events being raised. The parameters I have expressed here are the Microsoft standard, but you can use any parameters you like.

However, the method that receives the event MUST have exactly the same parameters as the event being raised.

Here's how you make events in VB. In the event declaration:

Public Event OnLoad(e As System.EventArgs, sender as Object)

In the event call: RaiseEvent OnLoad(New EventArgs(), Me) You can use any kind of parameters you want there.

Making a method respond to the event

Public Sub HelloWorld(e as System.EventArgs, sender as Object) Handles OtherObject.OnLoad

End Sub

OR:

AddHandler OtherObject.OnLoad, AddressOf MethodToHandleTheEvent

Hope this helps. Please comment if you have any more questions.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top