eran otzap
eran otzap

Reputation: 12533

C# Generic Methods Problem ,TargetException , Object does not match target type

iv'e been using the following reflection methods in order to create a Generic MethodInfo object of a certain type

// 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  

now since these are methods that i use Frequently i decided to encapsulate them in a factory class

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

now when i try to invoke the same method from somewhere outside the factory class i get a TargetException witch states, Object does not match target type.

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

is the target type the type of the place witch i call the invoke from ? and if so why should it matter the Method is found in the factory when i call GetType() inside GetGenericMethod i get the type of the factory and from there i extract the wanted method using a lambda expression .

i would really appreciate if some one could shed some light on the matter since i seem to be missing some know how on the matter

thanks in advance eran.

Upvotes: 4

Views: 3164

Answers (1)

Strillo
Strillo

Reputation: 2972

Try using

index_genrator.Invoke(f,null);

Upvotes: 3

Related Questions