UPDATE: The suggestion to use an expression tree to construct a lambda using the given MethodInfo
, in conjunction with the Expression<TDelegate>.Compile
method, proved to be a gold mine in my scenario. In the specific case where I was toying with this idea, I saw average execution time for a particular method go from ~0.25 ms to ~0.001 ms: about a 250x speed increase! Thanks to everyone for your help!
I realize that, generally speaking, there are performance implications of using reflection. (I myself am not a fan of reflection at all, actually; this is a purely academic question.)
Suppose there exists some class that looks like this:
public class MyClass {
public string GetName() {
return "My Name";
}
}
Bear with me here. I know that if I have an instance of MyClass
called x
, I can call x.GetName()
. Furthermore, I could set a Func<string>
variable to x.GetName
.
Now here's my question. Let's say I don't know the above class is called MyClass
; I've got some object, x
, but I have no idea what it is. I could check to see if that object has a GetName
method by doing this:
MethodInfo getName = x.GetType().GetMethod("GetName");
Suppose getName
is not null. Then couldn't I furthermore check if getName.ReturnType == typeof(string)
and getName.GetParameters().Length == 0
, and at this point, wouldn't I be quite certain that the method represented by my getName
object could definitely be cast to a Func<string>
, somehow?
I realize there's a MethodInfo.Invoke
, and I also realize I could always create a Func<string>
like:
Func<string> getNameFunc = () => getName.Invoke(x, null);
I guess what I'm asking is if there's any way to go from a MethodInfo
object to the actual method it represents, incurring the performance cost of reflection in the process, but after that point being able to call the method directly (via, e.g., a Func<string>
or something similar) without a performance penalty.
What I'm envisioning might look something like this:
// obviously this would throw an exception if GetActualInstanceMethod returned
// something that couldn't be cast to a Func<string>
Func<string> getNameFunc = (Func<string>)getName.GetActualInstanceMethod(x);
(I realize that doesn't exist; I'm wondering if there's anything like it.)
If what I'm asking doesn't make sense, or if I'm being unclear, I'll be happy to attempt to clarify.