简体   繁体   中英

Casting object in generics in C# - InvalidCast Exception

I have a generic userControl I made, that given a Type T (where T is a class), create a tree with all the types that implement T in the tree (obviously finding them with Reflection). The tree works fine, but when I tried to implement an event that tells me that a type was selected, Im getting an InvalidCastException, or that my function doesn't work, no matter what I do.

The function is:

void TypeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
      if ((typeSelected != null) && (e.Node.Tag is T))
           typeSelected((T)e.Node.Tag)
}

in e.Node.Tag there is an object that is really of type T typeSelected is of type Action<T>

so in this manner, e.Node.Tag is T is false on runtime, but is true when I set watch on it also, if I remove the condition Im getting the exception from (T)e.Node.Tag , although again, the watch succeeds in casting it.

the type in runtime is RuntimeType ....

so why is this happening, and how can I solve it?

This could happen if the type of e.Node.Tag is a derived type of T. If this is the case, you should look into Variants & CoVariants

You haven't assigned a value to T. You have to pass the generic assignment of T through to a method - not an event handler - in the method's signature.

void TypeView_NodeMouseClick(object sender, TreeNodeMouseClickEvenArgs e)
{     
    DoWhateverAfterMouseClicked<string>(sender, e);    
}

public void DoWhateverAfterMouseClicked<T>(object sender, TreeNodeClickEventArgs e)
{    
           if ((typeSelected != null) && (e.Node.Tag is T))
                    typeSelected((T)e.Node.Tag);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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