using System;
using System.Reflection;
// Define a class with a generic method.
public class Test
{
public static void Generic<T>(System.Windows.Controls.TextBlock outputBlock, T toDisplay)
{
outputBlock.Text += String.Format("\r\nHere it is: {0}", toDisplay) + "\n";
}
}
public class Example
{
public static void Demo(System.Windows.Controls.TextBlock outputBlock)
{
outputBlock.Text += "\r\n--- Examine a generic method." + "\n";
// Create a Type object representing class Test, and
// get a MethodInfo representing the generic method.
//
Type ex = typeof(Test);
MethodInfo mi = ex.GetMethod("Generic");
DisplayGenericMethodInfo(outputBlock, mi);
// Assign the int type to the type parameter of the Example
// method.
//
MethodInfo miConstructed = mi.MakeGenericMethod(typeof(int));
DisplayGenericMethodInfo(outputBlock, miConstructed);
// Invoke the method.
object[] args = {outputBlock, 42};
miConstructed.Invoke(null, args);
// Invoke the method normally.
Test.Generic<int>(outputBlock, 42);
// Get the generic type definition from the closed method,
// and show it's the same as the original definition.
//
MethodInfo miDef = miConstructed.GetGenericMethodDefinition();
outputBlock.Text += String.Format("\r\nThe definition is the same: {0}",
miDef == mi) + "\n";
}
private static void DisplayGenericMethodInfo(System.Windows.Controls.TextBlock outputBlock, MethodInfo mi)
{
outputBlock.Text += String.Format("\r\n{0}", mi) + "\n";
outputBlock.Text += String.Format("\tIs this a generic method definition? {0}",
mi.IsGenericMethodDefinition) + "\n";
outputBlock.Text += String.Format("\tIs it a generic method? {0}",
mi.IsGenericMethod) + "\n";
outputBlock.Text += String.Format("\tDoes it have unassigned generic parameters? {0}",
mi.ContainsGenericParameters) + "\n";
// If this is a generic method, display its type arguments.
//
if (mi.IsGenericMethod)
{
Type[] typeArguments = mi.GetGenericArguments();
outputBlock.Text += String.Format("\tList type arguments ({0}):",
typeArguments.Length) + "\n";
foreach (Type tParam in typeArguments)
{
// IsGenericParameter is true only for generic type
// parameters.
//
if (tParam.IsGenericParameter)
{
outputBlock.Text += String.Format("\t\t{0} parameter position {1}" +
"\n\t\t declaring method: {2}",
tParam,
tParam.GenericParameterPosition,
tParam.DeclaringMethod) + "\n";
}
else
{
outputBlock.Text += String.Format("\t\t{0}", tParam) + "\n";
}
}
}
}
}
/* This example produces the following output:
--- Examine a generic method.
Void Generic[T](T)
Is this a generic method definition? True
Is it a generic method? True
Does it have unassigned generic parameters? True
List type arguments (1):
T parameter position 0
declaring method: Void Generic[T](T)
Void Generic[Int32](Int32)
Is this a generic method definition? False
Is it a generic method? True
Does it have unassigned generic parameters? False
List type arguments (1):
System.Int32
Here it is: 42
Here it is: 42
The definition is the same: True
*/