在 ASP.NET WebForms 中,我们有时需要在 UserControl 中使用泛型类型参数。但是,这在 WebForms 中并不容易实现,因为 UserControl 在编译时是以单独的 DLL 文件编译的,无法在预编译阶段动态创建泛型类型参数。
为了解决这个问题,我们可以使用反射来动态创建泛型类型参数,如下所示:
public class MyUserControl
Assembly assembly = Assembly.GetExecutingAssembly(); Type type = assembly.GetType("MyNamespace.MyUserControl`1"); Type genericType = type.MakeGenericType(new Type[] { typeof(Int32) }); Control control = (Control)Activator.CreateInstance(genericType);
this.Controls.Add(control);
这样就可以创建一个具有泛型类型参数的 UserControl 并将其动态加载到程序集中。