Managed CodeGen

This blog is to introduce some new features about Managed CodeGen in Whidbey. We provided a new way of doing LightWeight CodeGen, added support for emitting Generics in Reflection.Emit and there is some new exciting token handle stories in Reflection going on.

GetMethod limitation regarding Generics

I've got several inquiry emails about this issue, so I think it is a good idea to publish the problem here.

Say we have:

public class Test

{
   public void Teste<U>(U teste, int i) { Console.WriteLine(teste); }

   public void Teste<U> (U teste) { }

}

Is it possible to use GetMethod to get void Teste<U>(U teste, int i)out?

Unfortunately, the answer is there is no way for now to use only GetMethod to get the method before we know the type of U.  It is a limitation in Reflection for Whidbey.

Here is a possible workaround for you, you can use GetMembers to minimize the methodinfo you have to retrieve.

using System;
using System.Reflection;

public class Test
{
    public void Teste<U>(U teste, int i) { Console.WriteLine(teste); }

    public void Teste<U> (U teste) { }

    public static void Main()
    {
 
        MemberInfo[] mis = typeof(Test).GetMember("Teste*", BindingFlags.InvokeMethod|BindingFlags.Public|BindingFlags.Instance);
        if (mis.Length == 0) {Console.WriteLine("No Teste Methods"); return;}

        Type U = ((MethodInfo)mis[0]).GetGenericArguments()[0]; // assume we know the class structure above, for simplicity.
        MethodInfo mInfo = typeof(Test).GetMethod("Teste", new Type[] { U, typeof(int) });

        if (mInfo.IsGenericMethod)
        {
             mInfo = mInfo.MakeGenericMethod(typeof(string));
             mInfo.Invoke(new Test(), new object[] {  "Test - calling generic method", 1 });
        }
    }
}

 

Published Wednesday, September 14, 2005 6:46 PM by yirutang

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

 

kfarmer said:

Uh.. How do I say this?

"Teste" is another word for "testicle".
September 14, 2005 2:54 PM

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required
Submit

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker