< DOCTYPE html PUBLIC -WCDTD XHTML StrictEN httpwwwworgTRxhtmlDTDxhtml-strictdtd> 通过泛型方法定义具有特定类型意义的方法是常用的手段。但在某些特定情况下,例如在一些通用的框架中,直到运行时才能确定泛型类型参数,就必须通过非泛型方式来调用泛型方法。

假定有这样一个方法:

public static void Add<T>(T obj, IList<T> list)

{

      list.Add(obj);

}

如果想换成这样调用:

Add(Type type, object obj, object list);通常的方法是这样的:

void Add(Type type, object obj, object list)

{

    MethodInfo mi = typeof(MyType).GetMethod("Add");

    MethodInfo gmi = mi.MakeGenericMethod(type);

    gmi.Invoke(new object[] { obj, list });

} ​​