I'm struggling to convert the below code to C#.
Class Class1
Implements IMyInterface
Public Event MyEvent(ByVal sender As Object, ByVal e As MyEventArgs) Implements IMyInterface.MyEvent
Public Sub New()
AddHandler Me.Slider.ValueChanged, AddressOf OnSliderValueChanged
End Sub
Private Sub OnSliderValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
RaiseEvent MyEvent(Me, New MyEventArgs())
End Sub
End Class
Here's what visual studio inserts when I ask it to implement for me:
event EventHandler<MyEventArgs> IMyInterface.MyEvent
{
add { throw new NotImplementedException(); }
remove { throw new NotImplementedException(); }
}
With a bit of googling I'm sure I can find out what to replace the NotImplementedException parts with but VS is still telling me that the definition is not implemented 开发者_运维百科anyway.
Odd that VS generated the add/remove accessors. You don't need them, the compiler automatically generates them. It should look like this:
public class Class1 : IMyInterface {
public event EventHandler<MyEventArgs> MyEvent;
public Class1() {
this.Slider.ValueChanged += OnSliderValueChanged;
}
private void OnSliderValueChanged(object sender, EventArgs e) {
var handler = MyEvent;
if (handler != null) {
handler(this, new MyEventArgs());
}
}
}
Using the "handler" variable avoids a null exception if a thread wires the event.
Edit: ah, it's because you implemented the event explicitly. Not necessary, the event should be public anyway. That's what got you in trouble, the C# syntax diverges here from VB.NET
The implementation that Visual Studio creates for you is not a complete implementation, but rather an implementation body which you need to complete. In this case, the lines "throw new NotImplementedException();" need to be replaced by your code.
Using:
http://www.developerfusion.com/tools/convert/vb-to-csharp/
I get:
class Class1 : IMyInterface
{
public event MyEventEventHandler IMyInterface.MyEvent;
public delegate void MyEventEventHandler(object sender, MyEventArgs e);
public Class1()
{
this.Slider.ValueChanged += OnSliderValueChanged;
}
private void OnSliderValueChanged(System.Object sender, System.EventArgs e)
{
if (MyEvent != null) {
MyEvent(this, new MyEventArgs());
}
}
}
精彩评论