I want to invoke methods with a certain attribute. So I'm cycling through all the assemblies and all methods to find the methods with my attribute. Works fine, but how do I invoke a certain method when I only got it's MethodInfo.
AppDomain app = AppDomain.CurrentDomain;
Assembly[] ass = app.GetAssemblies();
Type[] types;
foreach (Assembly a in ass)
{
types = a.GetTypes();
foreach (Type t in types)
{
MethodInfo[] methods = t.GetMethods();
foreach (MethodInfo method in methods)
{
// Invoke a certain method
}
}
}
The problem is that I don't know the instance of the class that contains that certain method. So I can't invoke it properly because the methods are not static. I also want to avoid creating a new instance of this class if possible.
This strikes me as an issue in terms of the problem definition rather than coding.
Instance methods depend on which instance they're called on - it makes no sense to call an instance method without caring about what it's called on. (As Martin says, an instance method which doesn't care which instance it's being called on should almost always be static. The only immediate exception I can think of for this is virtual methods, where the instance implicitly specifies which implementation to use.)
Work out what it really means in your context for there to be an annotated instance method. Why are you trying to invoke methods anyway? What's the bigger picture? What context do you have? I strongly suspect you'll want some notion of a context - a collection of objects which you can call the instance methods on.