C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C#Generic Methods问题,TargetException,Object与目标类型不匹配大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
iv我们一直在使用以下反射方法来创建某种类型的Generic MethodInfo对象

// this is the example that does work,i call the invoked generic method 
// from the same class it resides in 
// all i'm doing here is casTing type on T in order to create an object<t> of
// some sort witch i can't kNow the T till run-time
class someClass
{
    public IIndexable CreateIndex(String column)
    {
       Type type = GetType(column);
       MethodInfo index_generator = GetGenericMethod(type,"GenerateIndex");
       Iindexable index = (IindaxablE)index_genraotr.Invoke(this,null); 
    }


     public MethodInfo GetGenericMethod(Type type,String method_@R_696_8313@
     {
        return GetType()
              .getmethods(BindingFlags.Public |  BindingFlags.InstanceBindingFlags.NonPubliC)
              .Single(methodInfo => methodInfo.Name == method_name && methodInfo.IsGenericMethodDeFinition)
              .MakeGenericMethod(typE);
     }
     public Iindexable GenerateIndex<T>()
     {
         return new Sindex<T>();    
     }
 } // end someClass

现在因为这些是我经常使用的方法我决定将它们封装在工厂类中

class Factory
{// same deal as above just that Now i got a class called factory encapsulaTing 
 // all the functionality involved   
       public MethodInfo GetGenericMethod(Type type,String method_@R_696_8313@

       public IIndexable GenerateIndex<T>(String[] columns) 
       {// SIndex : IIndexable
            SIndex<T> index = new SIndex<T>(record,column,seecondary_columns);
            return index;
       }
       public Type GetType(String column)
}

现在当我尝试从工厂类之外的某个地方调用相同的方法时,我得到一个TargetException女巫状态,
对象与目标类型不匹配.

// some event,or some place to call the factory's functionality from 
btn_index ClickEvent(.......)
{              
    Factory f = new Factory();
    Type type = f.GetType(column);
    MethodInfo index_generator = f.GetGenericMethod(type,"GenerateIndex");
    Iindexable index = (IindexablE)index_genrator.Inovke(this,null);
}

目标类型是我称之为调用的地方的类型?
如果是这样,为什么在工厂中找到方法很重要
当我在GetGenericMethod中调用GetType()时,我得到了工厂的类型
从那里我使用lambda表达式提取想要的方法.

我真的很感激,如果有人能够对这个问题有所了解,因为我似乎错过了一些关于此事的知识

先谢谢伊兰.

解决方法

尝试使用

index_genrator.Invoke(f,null);

大佬总结

以上是大佬教程为你收集整理的C#Generic Methods问题,TargetException,Object与目标类型不匹配全部内容,希望文章能够帮你解决C#Generic Methods问题,TargetException,Object与目标类型不匹配所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。