c#泛型方法问题,TargetException,对象不匹配目标类型
本文关键字:不匹配 目标 类型 对象 TargetException 泛型方法 问题 | 更新日期: 2023-09-27 18:04:08
我一直在使用以下反射方法来创建特定类型的泛型MethodInfo对象
// 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
现在,因为这些是我经常使用的方法,我决定将它们封装在一个工厂类
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)
}
现在当我尝试从工厂类之外的某个地方调用相同的方法时,我得到一个TargetException巫婆状态,对象不匹配目标类型。
// 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);
}
目标类型是我调用的地方类型吗?如果是这样,为什么在工厂中找到方法很重要呢当我在GetGenericMethod中调用GetType()时,我得到工厂的类型从那里,我使用lambda表达式提取所需的方法。
如果有人能给我一些启示,我将非常感激,因为我似乎缺少一些关于这件事的知识
尝试使用
index_genrator.Invoke(f,null);