Mediator Helper class in Vb.net

本文关键字:Vb net in class Helper Mediator | 更新日期: 2023-09-27 18:28:04

我正在尝试实现一个中介助手类,以促进视图模型之间的信息传输。

从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的在线转换器提供

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<…>As var语句。我假设这是linqc#风格,它一直很难轻松翻译。这件事表面上吸引了我,因为无论如何,我仍在努力理解整个原则。有人能为这两条线提出一个合适的结构吗。

感谢

Mediator Helper class in Vb.net

在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