Sign in to follow this  
DanX2002

[.net] Generic Reflection

Recommended Posts

I have a static class called Utility. It contains a (static) method called calculate() which takes two generic types in < > when called, as well as some parameters. These generic types are constrained by using the "where" keyword. Let's call the two generic types Type1 and Type2. What I need to do is start a new thread, pass Type1 and Type2 to the new thread, and have that new thread call the static method using those two types in the < > when calling it. I've been trying to use reflection because I don't see any other way to pass in Type objects and use those as actual generic types on a method call. But I am stuck looking through the msdn's library MethodInfo class without success. How can I say something like: Thread myThread = .... (I already know how to make one) myThread.informOfTypes(Type type1, Type type2); myThread.doStuff(); then somewhere in myThread's code: MethodInfo info = (typeof(Utility)).GetMethod("calculate`2"); info.Invoke /*with type1 and type2 passed in somehow*/ (?, args); //the first argument of Invoke() is supposed to be the object, but calculate() is static because Utility is a static class. Can I pass in null? //the second argument is easy. But how do I call it *generically* with type1 and type2, so that Invoke calls Utility.calculate<type1, type2>(args); ? Can anyone help please?

Share this post


Link to post
Share on other sites
From the Help on Invoke:

Parameters
obj
Type: System: Object
The object on which to invoke the method or constructor. If a method is static, this argument is ignored. If a constructor is static, this argument must be nullNothingnullptra null reference (Nothing in Visual Basic) or an instance of the class that defines the constructor.


On passing the types.

Share this post


Link to post
Share on other sites
Call methodInfo.MakeGenericMethod:
http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.makegenericmethod.aspx

Share this post


Link to post
Share on other sites
@ernow

Thanks, that's one question down

@kanato

That sounds promising, thanks, I'll look into it and see if I can make it work

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this