C#Generic Methods问题,TargetException,Object与目标类型不匹配

C#Generic Methods问题,TargetException,Object与目标类型不匹配,第1张

概述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 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-timeclass 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_name)     {        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_name)       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与目标类型不匹配所遇到的程序开发问题。

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

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1230922.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存