开发者

How can I make this generic

开发者 https://www.devze.com 2023-04-06 10:46 出处:网络
I have a bunch of ViewModel classes, Q001ViewModel, Q002ViewModel, ..., QnnnViewModel.These all inherit from VMBase.

I have a bunch of ViewModel classes, Q001ViewModel, Q002ViewModel, ..., QnnnViewModel. These all inherit from VMBase.

I also have a set of Subs ShowQnnn, ShowQnnn, ..., ShowQnnn. An example is:

    Private Sub ShowQ001()
        Dim workspace As Q001ViewModel = _
            CType(Me.Workspaces.FirstOrDefault(Function(vm) vm.GetType() Is GetType开发者_如何学运维(Q001ViewModel)), Q001ViewModel)

        If workspace Is Nothing Then
            workspace = New Q001ViewModel(_dbc)
            Me.Workspaces.Add(workspace)
        End If

        Me.SetActiveWorkspace(workspace)
    End Sub

Workspaces is an ObservableCollection of VMBase.

The ShowQnnn procedures are used to display a ViewModel. The point is that a new QnnnViewModel will be added to the workspaces collection only if one of that type does not already exist.

Is there a way to turn then ShowQnnn procedures into one generic version?


Sorry but I don't know VB.Net syntax enough regarding generics (feel free to edit my answer with the VB.Net version), so i'll answer in C#.

If the constructors take different arguments the solution would look like :

void ShowQxxx<T>(Func<T> constructor)
    where T : VMBase
{
    var workspace = (T)(Workspaces.FirstOrDefault(vm => vm is T);

    if (workspace == null)
    {
        workspace = constructor();
        Workspaces.Add(workspace)
    }

    SetActiveWorkspace(workspace)
}

...

ShowQxxx(() => new Q001ViewModel(_dbc));

Otherwise you could simplify even more using reflection :

void ShowQxxx<T>()
    where T : VMBase
{
    var workspace = (T)(Workspaces.FirstOrDefault(vm => vm is T);

    if (workspace == null)
    {
        var ctor = typeof(T).GetConstructor(new [] { typeof(MyDataBaseType) });
        workspace = (T)(ctor.Invoke(_dbc));
        Workspaces.Add(workspace)
    }

    SetActiveWorkspace(workspace)
}

...

ShowQxxx<Q001ViewModel>();


Here is the VB version

    Private Sub ShowQxxx(Of T As VMBase)(constructor As Func(Of T))
        Dim workspace As T = _
            CType(Me.Workspaces.FirstOrDefault(Function(vm) vm.GetType() Is GetType(T)), T)

        If workspace Is Nothing Then
            workspace = constructor()
            Me.Workspaces.Add(workspace)
        End If

        Me.SetActiveWorkspace(workspace)
    End Sub
....

    ShowQxxx(Function() New Q001ViewModel(_dbc))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号