将类类型传递给方法参数

时间:2016-03-09 15:37:33

标签: c#

有没有办法将复杂类型作为参数传递给方法。 我想实现下面列出的更通用的方法。

我想将View(类)名称传递给方法,而不是在下面的情况下明确指定'ParticipantSummaryView'。谢谢

    private void InitializePdfView(ParticipantBasic selectedParticipant,
                                          string regionName, string viewName)
    {
        IRegion region = this.regionManager.Regions[regionName];
        if (region == null) return;

        // Check to see if we need to create an instance of the view.
        var view = region.GetView(viewName) as ParticipantSummaryView;
        if (view == null)
        {
            // Create a new instance of the EmployeeDetailsView using the Unity container.
            view = this.container.Resolve<ParticipantSummaryView>();

            // Add the view to the main region. This automatically activates the view too.
            region.Add(view, viewName);
        }
        else
        {
            // The view has already been added to the region so just activate it.
            region.Activate(view);
        }

        // Set the current employee property on the view model.
        var viewModel = view.DataContext as ParticipantSummaryViewModel;
        if (viewModel != null)
        {
            viewModel.CurrentParticipant = selectedParticipant;
        }
    }

1 个答案:

答案 0 :(得分:1)

您可以使用泛型:

 private void InitializePdfView<TView, TViewModel>(ParticipantBasic selectedParticipant, string regionName, string viewName)
{
    IRegion region = this.regionManager.Regions[regionName];
    if (region == null) return;

    // Check to see if we need to create an instance of the view.
    var view = region.GetView(viewName) as TView;
    if (view == null)
    {
        // Create a new instance of the EmployeeDetailsView using the Unity container.
        view = this.container.Resolve<TView>();

        // Add the view to the main region. This automatically activates the view too.
        region.Add(view, viewName);
    }
    else
    {
        // The view has already been added to the region so just activate it.
        region.Activate(view);
    }

    // Set the current employee property on the view model.
    var viewModel = view.DataContext as TViewModel;
    if (viewModel != null)
    {
        viewModel.CurrentParticipant = selectedParticipant;
    }
}

但是,您需要为TViewModel实施约束,因为无法在任何类型上调用.CurrentParticipant。您需要为viewModel变量dynamic创建或使用具有此类方法的viewmodel的适当接口或基类。

调用它可能看起来像:

InitializePdfView<ParticipantSummaryView, ParticipantSummaryViewModel>(selectedParticipant, regionName, viewName);