我正在尝试实现一个中介辅助类,以便在视图模型之间传输信息。
从c#
开始static public class Mediator
{
static IDictionary<string, List<Action<object>>> pl_dict = new Dictionary<string, List<Action<object>>>();
static public void Register(string token, Action<object> callback)
{
if (!pl_dict.ContainsKey(token))
{
var list = new List<Action<object>>();
list.Add(callback);
pl_dict.Add(token, list);
}
else
{
bool found = false;
foreach (var item in pl_dict[token])
if (item.Method.ToString() == callback.Method.ToString())
found = true;
if (!found)
pl_dict[token].Add(callback);
}
}
static public void Unregister(string token, Action<object> callback)
{
if (pl_dict.ContainsKey(token))
pl_dict[token].Remove(callback);
}
static public void NotifyColleagues(string token, object args)
{
if (pl_dict.ContainsKey(token))
foreach (var callback in pl_dict[token])
callback(args);
}
}
我最终在vb中得到以下内容(由telerik&#39的在线转换器提供
Public NotInheritable Class Mediator
Private Sub New()
End Sub
Shared pl_dict As IDictionary(Of String, List(Of Action(Of Object))) = New Dictionary(Of String, List(Of Action(Of Object)))()
Public Shared Sub Register(token As String, callback As Action(Of Object))
If Not pl_dict.ContainsKey(token) Then
Dim list = New List(Of Action(Of Object))()
list.Add(callback)
pl_dict.Add(token, list)
Else
Dim found As Boolean = False
For Each item As var In pl_dict(token)
If item.Method.ToString() = callback.Method.ToString() Then
found = True
End If
Next
If Not found Then
pl_dict(token).Add(callback)
End If
End If
End Sub
Public Shared Sub Unregister(token As String, callback As Action(Of Object))
If pl_dict.ContainsKey(token) Then
pl_dict(token).Remove(callback)
End If
End Sub
Public Shared Sub NotifyColleagues(token As String, args As Object)
If pl_dict.ContainsKey(token) Then
For Each callback As var In pl_dict(token)
callback(args)
Next
End If
End Sub
End Class
编译器不喜欢两个For Each&lt; ...&gt;作为var语句。我假设这是linq c#风格,一直很难轻易翻译。这个表面上是因为我仍然试图理解整个原则。任何人都可以为这两条线提出适当的构造。
由于
答案 0 :(得分:2)
在VB中,等效于var
的目的是简单地声明变量而不指定类型,例如:
For Each callback In pl_dict(token)
callback(args)
Next
但是,要使其正常工作,您需要Option Infer On
。或者,您可以只指定迭代器变量的类型(实际上是Action(Of Object)
),如下所示:
For Each callback As Action(Of Object) In pl_dict(token)
callback(args)
Next