加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 07:35:44 所属栏目:百科 来源:网络整理
导读: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 a
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_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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读