1

EDIT: the class/method that i'm trying to run this inside is static and therefore i'm unable to pass this into the generic.Invoke

I have a static Data Access Class that i use to automatically parse data from various sources. i was starting to re-factor it when i ran into a problem. Im tring to pass a Type to a Generic method via reflection, (the method then parses the type and returns the Type with a value) my code currently looks like

Type type1 = typeof( T );
var item = (T)Activator.CreateInstance( typeof( T ), new object[] { } );

foreach (PropertyInfo info in type1.GetProperties())
{
    Type dataType = info.PropertyType;
    Type dataType = info.PropertyType;
    MethodInfo method = typeof( DataReader ).GetMethod( "Read" );
    MethodInfo generic = method.MakeGenericMethod( dataType ); 
    //The next line is causing and error as it expects a 'this' to be passed to it
    //but i cannot as i'm inside a static class
    generic.Invoke( this, info.Name, reader );
    info.SetValue(item,DataReader.Read<dataType>(info.Name, reader ) , null);
}
RoughPlace
  • 1,111
  • 1
  • 13
  • 23
  • possible duplicate of [How to use reflection to call generic Method?](http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method) – Sam Harwell Mar 22 '13 at 15:22

2 Answers2

2

I guess DataReader.Read is the static method, right?

Therefore, change the error line like below, since you are calling the static method. There is not object, so you just pass null into Invoke method:

var value = generic.Invoke( null, new object[] {info.Name, reader} );
cuongle
  • 74,024
  • 28
  • 151
  • 206
0

The type parameter to a generic method isn't an instance of Type; you can't use your variable in this way. However, you can use reflection to create the closed-generic MethodInfo you require (that is, with the type parameter specified), which would look something like this:

// this line may need adjusting depending on whether the method you're calling is static
MethodInfo readMethod = typeof(DataReader).GetMethod("Read"); 

foreach (PropertyInfo info in type1.GetProperties())
{
    // get a "closed" instance of the generic method using the required type
    MethodInfo genericReadMethod m.MakeGenericMethod(new Type[] { info.PropertyType });

    // invoke the generic method
    object value = genericReadMethod.Invoke(info.Name, reader);

    info.SetValue(item, value, null);
}
Dan Puzey
  • 33,626
  • 4
  • 73
  • 96