我有很多类,我想创建一个“目录”。
这样我就可以自动创建菜单。
然后单击菜单项将创建类的一个实例并显示窗口。
我想要的是一个System.Type数组,我可以在其中填充所有的类,而不需要实例化它们。
尽管从我的测试和(不成功的)谷歌搜索来看,这似乎是不可能的。
有什么想法吗?
发布于 2010-04-16 06:42:38
这对您创建一个简单的映射有效吗?ArrayList不是通用的,但您可以在其中创建一个自定义对象。
var mapper = new System.Collections.Generic.Dictionary<string, System.Type>();
mapper.Add("show-about-box", typeof(MyApp.Forms.AboutBox));然后,您可以使用refleciton来创建类的实例,使用如下代码:
// Create an instance using [Activator.CreateInstance][1].
System.Type toCreate = mapper["show-about-box"];
Object o = Activator.CreateInstance(toCreate);
// Or, using try-get to be safer
System.Type toCreate = null;
if ( mapper.TryGetValue("show-about-box", out toCreate) ) {
Object o = Activator.CreateInstance(toCreate);
}发布于 2010-04-16 06:36:07
是的,如果我没理解错的话,这是可以做到的。从System.Reflection类及其GetExportedTypes方法开始,看一下程序集名称空间中的类。这为您提供了一个从指定的System.Type - http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getexportedtypes.aspx中公开声明的程序集对象的数组
https://stackoverflow.com/questions/2649431
复制相似问题