简体   繁体   English

在 C# 中将 object 转换为 generics - InvalidCast 异常

[英]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).我有一个我制作的通用 userControl,它给定一个类型 T(其中 T 是一个类),创建一个树,其中包含在树中实现 T 的所有类型(显然用反射找到它们)。 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.树工作正常,但是当我尝试实现一个告诉我选择了一个类型的事件时,我得到一个 InvalidCastException,或者我的 function 不起作用,无论我做什么。

The function is: function 是:

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>e.Node.Tag中有一个 object 确实是T类型typeSelectedAction<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.所以以这种方式, e.Node.Tag is T 在运行时为假,但当我对其设置 watch 时也是如此,如果我删除条件我从(T)e.Node.Tag得到异常,尽管再次,手表成功铸造它。

the type in runtime is RuntimeType ....运行时的类型是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如果 e.Node.Tag 的类型是 T 的派生类型,则可能会发生这种情况。如果是这种情况,您应该查看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.您尚未为 T 分配值。您必须将 T 的通用分配传递给方法签名中的方法 - 而不是事件处理程序。

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);

}

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

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