Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to call a generic method through reflection
    primarykey
    data
    text
    <p>is it possible to call with reflection a method with "explict type argument" <code>&lt;S&gt;</code> definition<br> e.g. <code>oObject.Cast&lt;S&gt;()</code> ?</p> <p>where is:</p> <pre><code>IList &lt;P&gt; oObject = new List &lt;P&gt;(); </code></pre> <p>I tried with</p> <pre><code>oObject.getType().InvokeMember( "Cast", BindingFlags.InvokeMethod, null, oObject, null) </code></pre> <p>but it does not work, does anyone know why?</p> <hr> <p>Here is the complete test code but still it does not work. The last line produce always exception. Is it possible to make it work ?</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace reflection_tester { class CBase { public string Ja = "I am the base"; } class MyClass01 : CBase { public string _ID; public string ID { get { return _ID; } set { _ID = value; } } } class Program { public static object wrapper() { //return a list of classes MyClass01 IList&lt;MyClass01&gt; lstClass01 = new List&lt;MyClass01&gt;(); MyClass01 oClass01a = new MyClass01(); oClass01a.ID = "1"; MyClass01 oClass01b = new MyClass01(); oClass01b.ID = "2"; lstClass01.Add(oClass01a); lstClass01.Add(oClass01b); return lstClass01; } static void Main(string[] args) { MyClass01 oMy1 = new MyClass01(); oMy1._ID = "1"; MyClass01 oMy2 = new MyClass01(); oMy2._ID = "3"; IList&lt;MyClass01&gt; oListType01 = new List&lt;MyClass01&gt;(); oListType01.Add(oMy1); oListType01.Add(oMy2); object oObjectType = new object(); oObjectType = oListType01; /* this works */ IEnumerable&lt;CBase&gt; enumList = oListType01.Cast&lt;CBase&gt;(); MethodInfo mInfo = typeof(System.Linq.Enumerable).GetMethod("Cast", new[] { typeof(System.Collections.IEnumerable) }).MakeGenericMethod(typeof(CBase)); /* this does not work, why ? throws exception */ IEnumerable&lt;CBase&gt; enumThroughObject = (IEnumerable&lt;CBase&gt;)mInfo.Invoke(oObjectType, null); return; } } } </code></pre>
    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