Ask Learn
Preview
Ask Learn is an AI assistant that can answer questions, clarify concepts, and define terms using trusted Microsoft documentation.
Please sign in to use Ask Learn.
Sign inThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
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 });
}
}
}
Ask Learn is an AI assistant that can answer questions, clarify concepts, and define terms using trusted Microsoft documentation.
Please sign in to use Ask Learn.
Sign in