iv'e used the following reflection methods to create a specific type of Generic MethodInfo object
// 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
Now, since these are the methods that I often use. I decided to encapsulate them in a factory class
class Factory {
now when I try to call the same method somewhere outside the factory class, I get the witches states of TargetException , the Object does not match the type of target.
// some event , or some place to call the factory 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); }
- type of target, type of place from which I am calling? and if so, why is this important, the method is found in the factory when I call GetType () inside GetGenericMethod, I get the type factory and from there I retrieve the desired method using the lambda expression.
I would really appreciate it if someone could shed light on this issue, since I do not seem to know how to do this.
thanks in advance eran.
source share