vendredi 18 mai 2018

Passing Type to Generic Method C#

I have a method that accepts a generic TViewModel class like so:

Page GetPage<TViewModel>() where TViewModel : class, IViewModelBase;

In my class I get the type of the item that the user selected (from a navigation list) like so:

var viewModel = item.TargetType;

This type will always be a view model that inherits from IViewModelBase

When I call this next line I need to be able to pass in the viewModel type. Im trying to do

var page = Navigator.GetPage<viewModel>();

But I get the following error:

viewModel is a variable but is being used like a type.

Is there anyway I can pass the viewModel type to the GetPage Method?

If not the only way I can see to do this is to have a switch statement that checks the viewModel type name and hard code the correct TViewModel into the GetPage call.

For example something like this:

switch (viewModel.Name)
{
    case "TaskViewModel":
            page = Navigator.GetPage<TaskViewModel>();
       break;
    case "TaskEditViewModel":
            page = Navigator.GetPage<TaskEditViewModel>();
       break;
}





Aucun commentaire:

Enregistrer un commentaire