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);
}
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
intoInvoke
method: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-genericMethodInfo
you require (that is, with the type parameter specified), which would look something like this: