Reputation: 2309
I want to invoke a method on a class that i have a reference to. The method that I want to call has a custom attributes. Currently I can find this attributes and call the property of my class Attribute.
is there a way to invoke that method ?
PS/ The project is written in vbnet, but I think the solution is the same in c#.
Upvotes: 2
Views: 2155
Reputation: 67148
If you can find the attributes I guess you have the MethodInfo
of that method(s). Simply call the MethodInfo.Invoke
method, you have to specify the instance of the object you want to use (or null
if it's a static method) and all the parameters to pass to the method (in the same order of the prototype).
For example if you have to invoke a method with this prototype:
void Foo(string name, int value);
And you have a function to find that method (making a search for a given attribute):
MethodInfo FindMethodWithAttribute(Type attributeType, Type objectType);
You can find and invoke that method (of a hypothetical object anObject
) with this code:
MethodInfo method = FindMethodWithAttribute(
typeof(MyAttribute), // Type of the "marker" attribute
anObject.GetType()); // Type of the object may contain the method
method.Invoke(anObject, new object[] { "someText", 2 });
Upvotes: 2