简体   繁体   中英

Converting VB.NET code to C#: Cannot convert lambda expression to type 'Delegate' because it is not a delegate type

Okay, so I've got I got a VB project that I'm converting to C#. So far, so good. The problem is delegates/actions are quite different between the two languages and I'm struggling to work out the difference.

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

And in 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));
}

The last line above is causing the CS1660 Cannot convert lambda expression to type 'Delegate' because it is not a delegate type error.

Your register method should be defined as:

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

Or you need to explicitly wrap your lambda in an Action :

private void Setup()
{
    Register(5, new Action<string>((string a) => LogName(a)));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM