Cannot perform explicit cast

Can you explain to me why in this piece of code:

private Dictionary<Type, Type> viewTypeMap = new Dictionary<Type, Type>();

public void ShowView<TView>(ViewModelBase viewModel, bool showDialog = false)
    where TView : IView
{
    var view = Activator.CreateInstance(viewTypeMap[typeof(TView)]);
    (IView)view.ShowDialog();
}

I get an error message:

"Only the destination, call, increment, decrement and new expression object can be used as an operator."

IView defines the ShowDialog () method.

+5
source share
4 answers

A translation operator has a lower priority than an element access operator.

(A)B.C();

analyzed as

(A)(B.C());

which is not a legal expression. You have to write

((A)B).C();

if you want to give Bin A, then call C()by type A.

For your future reference, the priority table is here:

http://msdn.microsoft.com/en-us/library/aa691323(v=VS.71).aspx

+12

, IView ?

public void ShowView<TView>(ViewModelBase viewModel, bool showDialog = false) where TView : IView
{
    var view = (IView)Activator.CreateInstance(viewTypeMap[typeof(TView)]);
    view.ShowDialog();
}
+2

You can use it when it is created, and then if it is used several times, you will not need to redo it every time.

var view = (IView)Activator.CreateInstance(viewTypeMap[typeof(TView)]);
view.ShowDialog();
0
source

Change

(IView)view.ShowDialog();

to

((IView) view).ShowDialog();

Eric explained why

-1
source

All Articles