Can you get a Func<T> (or similar) from a MethodInfo object?
Posted
by Dan Tao
on Stack Overflow
See other posts from Stack Overflow
or by Dan Tao
Published on 2010-05-29T00:06:23Z
Indexed on
2010/05/29
0:12 UTC
Read the original article
Hit count: 179
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.
© Stack Overflow or respective owner