Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Unfortunately System.Reflection doesn't provide a good way to correlate a method on a constructed type with the corresponding method on the generic type definition from which it was constructed. There are two solutions I know of, neither one is perfect:</p> <p><strong>Solution #1: static TypeBuilder.GetMethod.</strong> There's <a href="http://msdn.microsoft.com/en-us/library/ms145835.aspx" rel="nofollow noreferrer">a static version of GetMethod on TypeBuilder</a> that accepts a generic constructed type and a MethodInfo for a method on a generic type definition, and returns the corresponding method on the specified generic type. In this example, calling <code>TypeBuilder.GetMethod(Foo&lt;int&gt;, Foo&lt;T&gt;.Bar(T))</code> will give you <code>Foo&lt;int&gt;.Bar(T-as-int)</code> which you can then use to disambiguate between it and <code>Foo&lt;int&gt;.Bar(int)</code>. </p> <p>(The above example will not compile, naturally; I've used <code>Foo&lt;int&gt;</code> and <code>Foo&lt;T&gt;.Bar(T)</code> to mean the respective Type and MethodInfo objects which, which are easily obtainable but would make the example too complex). </p> <p>The bad news is that this only works when the generic type definition is a TypeBuilder, i.e. when you're emitting a generic type. </p> <p><strong>Solution #2: MetadataToken.</strong> It's a little known fact that type members retain their MetadataToken in the transition from generic type definitions to generic constructed types. So in your example, <code>Foo&lt;T&gt;.Bar(T)</code> and <code>Foo&lt;int&gt;.Bar(T-as-int)</code> should share the same MetadataToken. That would allow you to do this:</p> <pre><code>var barWithGenericParameterInfo = typeof(Foo&lt;&gt;).GetMethods() .Where(mi =&gt; mi.Name == "Bar" &amp;&amp; mi.GetParameters()[0].ParameterType.IsGenericParameter); var mappedBarInfo = foo.GetType().GetMethods() .Where(mi =&gt; mi.MetadataToken == genericBarInfo.MetadataToken); </code></pre> <p>(This will not compile either, unless I'm extremely lucky and managed to get it right the first time :) )</p> <p>The problem with this solution is that MetadataToken wasn't meant for that (probably; the documentation is a little skimpy on that) and it feels like a dirty hack. Nevertheless, it works.</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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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