c# - 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.
解决方案
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.
推荐阅读
- python - doc2vec 模型是否对非字典单词提供准确性?
- bash - 让 Gitlab 项目调用存储在中心位置的相同 gitlab-ci.yml
- c# - 使用 Html Agility Pack 解析特殊字符时的奇怪输出
- php - 使用 json_decode 的变量
- python - 我正在寻找一种从我的笔记本电脑连接到我的数据库的方法,这个数据库在 CPANEL 上,我正在制作一个 Django 项目
- jquery - 从服务器端 yajra 数据表下载所有 redords 的问题
- sql - HiveSQL - 无效的列引用
- javascript - 跨域 iframe 分区 IndexedDB
- javascript - 每 10 秒从 Google Fit REST API 检索健康数据
- go - 将时间戳写入数据库 - gocql vs cqlsh