Jump to content
  • Advertisement
Sign in to follow this  
DanX2002

[.net] Generic Reflection

This topic is 2995 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!