将静态反射信息传递给静态泛型方法 [英] passing static reflection information to static generic methods
问题描述
I有一个静态数据访问类,我用它来自动解析各种来源的数据。
当我遇到问题时,我开始重新考虑它。
通过反射将类型传递给泛型方法
(该方法解析类型并返回带有值的类型)
我的代码当前看起来像
类型type1 = typeof(T);
var item =(T)Activator.CreateInstance(typeof(T),new object [] {});
foreach(PropertyInfo info in type1.GetProperties())
{
Type dataType = info.PropertyType;
类型dataType = info.PropertyType;
MethodInfo method = typeof(DataReader).GetMethod(Read);
MethodInfo generic = method.MakeGenericMethod(dataType);
//下一行导致错误,因为它期望将一个'this'传递给它
//但是我不能像我在一个静态类中
generic.Invoke这个,info.Name,reader);
info.SetValue(item,DataReader.Read< dataType>(info.Name,reader),null);
}
c> DataReader.Read 是静态方法,对吗?
因此,请改变下面的错误行,因为您正在调用静态方法。没有对象,所以你只需将 null
传递给 Invoke
方法:
var value = generic.Invoke(null,new object [] {info.Name,reader});
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
into Invoke
method:
var value = generic.Invoke( null, new object[] {info.Name, reader} );
这篇关于将静态反射信息传递给静态泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!