我有一堆ViewModel类,Q001ViewModel,Q002ViewModel,...,QnnnViewModel。这些都继承自VMBase。
我还有一套Subs ShowQnnn,ShowQnnn,...,ShowQnnn。一个例子是:
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
工作区是VMBase的ObservableCollection。
ShowQnnn过程用于显示ViewModel。关键是只有当其中一种类型尚不存在时,才会将新的QnnnViewModel添加到工作空间集合中。
有没有办法将ShowQnnn程序转换为一个通用版本?
答案 0 :(得分:3)
很抱歉,但我不了解VB.Net语法的泛型(可以随意用VB.Net版本编辑我的答案),所以我会用C#回答。
如果构造函数采用不同的参数,解决方案将如下所示:
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));
否则你可以使用反射简化更多:
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>();
答案 1 :(得分:2)
这是VB版本
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))