Note that there are some explanatory texts on larger screens.

plurals
  1. POCan you get a Func<T> (or similar) from a MethodInfo object?
    primarykey
    data
    text
    <p>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.)</p> <p>Suppose there exists some class that looks like this:</p> <pre><code>public class MyClass { public string GetName() { return "My Name"; } } </code></pre> <p>Bear with me here. I know that if I have an instance of <code>MyClass</code> called <code>x</code>, I can call <code>x.GetName()</code>. Furthermore, I could set a <code>Func&lt;string&gt;</code> variable to <code>x.GetName</code>.</p> <p>Now here's my question. Let's say I <em>don't</em> know the above class is called <code>MyClass</code>; I've got some object, <code>x</code>, but I have no idea what it is. I could check to see if that object has a <code>GetName</code> method by doing this:</p> <pre><code>MethodInfo getName = x.GetType().GetMethod("GetName"); </code></pre> <p>Suppose <code>getName</code> is not null. Then couldn't I furthermore check if <code>getName.ReturnType == typeof(string)</code> and <code>getName.GetParameters().Length == 0</code>, and at this point, wouldn't I be quite certain that the method represented by my <code>getName</code> object could <em>definitely</em> be cast to a <code>Func&lt;string&gt;</code>, somehow?</p> <p>I realize there's a <code>MethodInfo.Invoke</code>, and I also realize I could always <em>create</em> a <code>Func&lt;string&gt;</code> like:</p> <pre><code>Func&lt;string&gt; getNameFunc = () =&gt; getName.Invoke(x, null); </code></pre> <p>I guess what I'm asking is if there's any way to go <strong>from</strong> a <code>MethodInfo</code> object <strong>to</strong> the actual method it represents, incurring the performance cost of reflection in the <em>process</em>, but <em>after</em> that point being able to call the method directly (via, e.g., a <code>Func&lt;string&gt;</code> or something similar) <em>without</em> a performance penalty.</p> <p>What I'm envisioning might look something like this:</p> <pre><code>// obviously this would throw an exception if GetActualInstanceMethod returned // something that couldn't be cast to a Func&lt;string&gt; Func&lt;string&gt; getNameFunc = (Func&lt;string&gt;)getName.GetActualInstanceMethod(x); </code></pre> <p>(I realize that doesn't exist; I'm wondering if there's anything <em>like</em> it.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload