简体   繁体   English

在运行时将参数传递给通用方法

[英]Pass Parameter to Generic Method at Runtime

I'm trying to refactor the following code into a single method 我正在尝试将以下代码重构为单个方法

if (message.Type == WindowType.DataSourcePickerTest)
{
    var vm = SimpleIoc.Default.GetInstance<DataSourcePickerViewModel>();
    var win = new PickerWindowTest { DataContext = vm };
    var result = win.ShowDialog() ?? false;
    if (result)
        Messenger.Default.Send(vm);
}
else if (message.Type == WindowType.BaselineSave)
{
    var vm = SimpleIoc.Default.GetInstance<BaselineSaveAsViewModel>();
    var win = new BaselineSaveAs { DataContext = vm };
    var result = win.ShowDialog() ?? false;
    if (result)
        Messenger.Default.Send(vm);
}

The only difference between the two branches is the type of the ViewModel and Window (vm and win). 两个分支之间的唯一区别是ViewModel和Window的类型(vm和win)。 So far I have 到目前为止我有

private void LaunchWindow(Type viewModelType, Type windowType)
{
    var vm = SimpleIoc.Default.GetInstance<viewModelType>();
}

but I'm getting a compilation error 'The type or namespace name 'viewModelType' could not be found'. 但我得到一个编译错误'无法找到类型或命名空间名称'viewModelType'。 Is there a way to refactor this if statement without resorting to reflection? 有没有办法在不诉诸反射的情况下重构这个if语句? Thanks in advance 提前致谢

You could factor out the inner part and call it generically, but it requires that the window class inherit from some base type that have a DataContext property (you might also need restrictions on T depending on the type of the DataContext property): 您可以将内部部分分解并一般地调用它,但它要求窗口类继承一些具有DataContext属性的基类型(您可能还需要对T限制,具体取决于DataContext属性的类型):

if (message.Type == WindowType.DataSourcePickerTest)
{
    SubMethod<DataSourcePickerViewModel, PickerWindowTest>();
}
else if (message.Type == WindowType.BaselineSave)
{
    SubMethod<BaselineSaveAsViewModel, BaselineSaveAs>();
}

public void SubMethod<T, U>() where U : Window, new()
{
    var vm = SimpleIoc.Default.GetInstance<T>();
    var win = new U { DataContext = vm };
    var result = win.ShowDialog() ?? false;
    if (result)
        Messenger.Default.Send(vm);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM