将VB.NET代码转换为C#:无法将lambda表达式转换为' Delegate'因为它不是委托类型

时间:2017-01-05 03:36:13

标签: c# vb.net delegates

好的,所以我得到了一个我转换为C#的VB项目。到现在为止还挺好。问题是两种语言之间的代理人/行动是完全不同的,我正在努力解决这些问题。

Private methods As New Dictionary(Of Integer, [Delegate])

Private Sub Register(id As Integer, method As [Delegate])
    methods.Add(id, method)
End Sub

Private Sub LogName(name As String)
    Debug.Print(name)
End Sub

Private Sub Setup()
    Register(Sub(a As String) LogName(a))
End Sub

在C#中

private Dictionary<int, Delegate> methods;

private void Register(int id, Delegate method)
{
    methods.Add(id, method);
}

private void LogName(string name)
{
    Debug.Print(name);
}

private void Setup()
{
    Register((string a) => LogName(a));
}

上面的最后一行导致CS1660 Cannot convert lambda expression to type 'Delegate' because it is not a delegate type错误。

1 个答案:

答案 0 :(得分:1)

您的注册方法应定义为:

private void Register(int id, Action<string> method)
{
    methods.Add(id, method);
}

或者你需要在Action

中明确地包装你的lambda
private void Setup()
{
    Register(5, new Action<string>((string a) => LogName(a)));
}