2017-01-05 25 views
0

さて、VBプロジェクトをC#に変換しています。ここまでは順調ですね。問題はデリゲート/アクションが2つの言語間でかなり異なっていることです。違いを解決するためには苦労しています。VB.NETコードをC#に変換:ラムダ式をデリゲート型ではないため 'Delegate'型に変換できません

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

あなたは 'レジスタ(新しいアクション((文字列A)しようとしたんでした=> LogName(a);))); ' –

+0

はい、いいえ、行かないでください。同じエラーのバリエーション。 –

答えて

1

あなたのregisterメソッドのように定義する必要があります。

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

それとも、明示的Actionであなたのラムダをラップする必要があります。

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

ありがとう、2番目の部分は解決策です。 –

+1

キャストも機能します:Register(0、(Action )((文字列a)=> LogName())); –

関連する問題