我在一个解决方案中有两个项目,project A
and project B
(using VS2010 Ultimate and C# windows application
).
Project B
充当用户管理应用程序project A
.
In project B
我有一个表格,其中包含chekcedlistbox
将列出所有的控件project A
表单名称和文本(此表单将允许系统管理员根据用户的安全组授予用户允许查看/编辑的表单)
这是我的代码:
private void GetFormNames()
{
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (Type t in a.GetTypes())
{
if (t.BaseType == typeof(Form))
{
var emptyCtor = t.GetConstructor(Type.EmptyTypes);
if (emptyCtor != null)
{
var f = (Form)emptyCtor.Invoke(new object[] { });
string FormText = f.Text;
string FormName = f.Name;
checkedListBox1.Items.Add("" + FormText + "//" + FormName + "");
}
}
}
}
}
我得到的结果是我当前项目的表单名称(B)和空行(//)和Select Window//MdiWindowDialog
, PrintPreview
.
我假设你已经参考过ProjectA
正确,并且您感兴趣的所有表格实际上都有一个public
无参数构造函数。该问题可能是由ProjectA
尚未加载,您可以通过多种方式修复此问题。可能最直接的就是使用static Assembly.Load http://msdn.microsoft.com/en-us/library/ky3942xh.aspx(只要文件位于同一目录中,否则就会变得更复杂)。
try
{
Assembly projectA = Assembly.Load("ProjectA"); // replace with actual ProjectA name
// despite all Microsoft's dire warnings about loading from a simple name,
// you should be fine here as long as you don't have multiple versions of ProjectA
// floating around
foreach (Type t in projectA.GetTypes())
{
if (t.BaseType == typeof(Form))
{
var emptyCtor = t.GetConstructor(Type.EmptyTypes);
if (emptyCtor != null)
{
var f = (Form)emptyCtor.Invoke(new object[] { });
// t.FullName will help distinguish the unwanted entries and
// possibly later ignore them
string formItem = t.FullName + " // " + f.Text + " // " + f.Name;
checkedListBox1.Items.Add(formItem);
}
}
}
}
catch(Exception err)
{
// log exception
}
另一个(可能更干净的解决方案)是让您感兴趣的所有表单都从单个基本表单继承。然后您可以从已知的程序集加载程序集Type
并检查每个枚举Type
在将其添加到列表之前继承它。然而,这是一个更广泛的变化,并且涉及ProjectA
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)