【问题标题】:C# Generic Methods Problem ,TargetException , Object does not match target typeC#泛型方法问题,TargetException,对象与目标类型不匹配
【发布时间】:2011-10-15 18:51:12
【问题描述】:

为了创建某种类型的通用 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 表达式提取想要的方法。

如果有人能对此事有所了解,我将不胜感激,因为我似乎错过了一些关于此事的知识

提前谢谢eran。

【问题讨论】:

  • 我对样本非常不清楚;您是否有机会用 reproducible 示例重新措辞,即我可以在哪里运行它并查看您所看到的异常?
  • 我没有感觉到的方法是多余的,如果您认为它会有所帮助,请编辑问题以显示所有图片
  • 我发现答案stackoverflow.com/questions/3860695/…目标是通过发送它来保存通用方法的类。除了 method.Invoke(this,new object[]{columns});我让它工作了,我还不明白目标问题,我认为这是调用方法后它需要返回的地方..有人知道目标的原因吗?
  • 目标不是在方法被调用后它需要返回的地方。它实际上是调用方法的对象。因为你从另一个类传递this已经定义了GenerateIndex&lt;T&gt;(),它给出了错误,因为目标类型是您的工厂类,而您调用的类(this)与该类不匹配

标签: c# generics reflection


【解决方案1】:

尝试使用

index_genrator.Invoke(f,null);

【讨论】:

  • 谢谢,是的,实际上已经在上面的 cmets 中得到了回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-06
  • 2019-02-25
  • 2017-02-04
相关资源
最近更新 更多