首页 > 解决方案 > Conversion between VB.net TO C# (new EventHandler) NO overload matches delegate

问题描述

I am new to C# and I need to convert my code from VB.NET to C#.

Here is my VB.NET code

Private Sub Receive()
    Dim inp As NetworkStream
    Dim income As BinaryReader
    inp = TCP.GetStream
    income = New BinaryReader(inp)

    While (State = "Connected")
        Try
            msg = income.ReadChar
            Application.OpenForms(0).Invoke(New EventHandler(AddressOf prin))
        Catch ex As Exception
            Try
                Me.Det = False
                If TCpThread.IsAlive = True Then TCpThread.Abort()
                TCP.Close()
                msg = ex.Message
            Catch ex1 As Exception
                Application.OpenForms(0).Invoke(New EventHandler(AddressOf prin))
            End Try
            State = "IDLE"
        End Try
    End While
End Sub

Private Sub prin()
    Message &= msg
    Check(Message)
End Sub

It works fine, I converted it to:

private void Receive()
{
    NetworkStream inp = default(NetworkStream);
    BinaryReader income = default(BinaryReader);
    inp = TCP.GetStream();
    income = new BinaryReader(inp);

    while (State == "Connected")
    {
        try
        {
            msg = System.Convert.ToString(income.ReadChar());
            Application.OpenForms[0].Invoke(new EventHandler(prin));
        }
        catch (Exception ex)
        {
            try
            {
                this.Det = false;
                if (TCpThread.IsAlive == true)
                {
                    TCpThread.Abort();
                }
                TCP.Close();
                msg = ex.Message;
            }
            catch (Exception)
            {
                Application.OpenForms[0].Invoke(new EventHandler(prin));
            }
            State = "IDLE";
        }
    }
}

private void prin()
{
    Message += msg;
    Check(Message);
}

But I get

Error 1 No overload for 'prin' matches delegate 'System.EventHandler'

for this line Application.OpenForms[0].Invoke(new EventHandler(prin));. Based on the multi-threading I need to invoke a function in order to follow my thread while it is running.

what is my mistake?

Any help will appreciate.

标签: c#vb.net

解决方案


Use

Application.OpenForms[0].Invoke(new Action(prin));

The type EventHandler represents a delegate with two parameters (a generic object and an EventArgs object). Your method prin doesn't match that description.

If you just want to create a delegate for your method, use a delegate type that has the same arguments as your method (in this case none). In this case, this is the Action delegate.

The Action delegate should also have been used in the VB code in the first place:

Application.OpenForms(0).Invoke(New Action(AddressOf prin))

However, using EventHandler works in VB because the AddressOf operator in VB is not really type safe.


推荐阅读