passing static reflection information to static ge

2019-08-04 16:38发布

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

2条回答
forever°为你锁心
2楼-- · 2019-08-04 17:27

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} );
查看更多
迷人小祖宗
3楼-- · 2019-08-04 17:42

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);
}
查看更多
登录 后发表回答