【发布时间】:2014-12-11 17:51:29
【问题描述】:
基本上我有一个类库,其中包含我编写的各种应用程序的大量“工具包”,然后我通常引用这个类库然后创建一个空白的 winforms 应用程序并更改 program.cs 以创建工具包的实例必需的。我想做的是创建一个可以根据参数或设置xml文件运行所有工具包的单个exe(这不是问题)问题是从字符串中的不同库创建类的实例。我要问的是,这可能吗?到目前为止我尝试了什么:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Advent.GlobalSettings.TestEnvironment = false;
string namespaceName = "GlobalLib.Toolkits.XmlService.Main";
//first attempt
Assembly ass = Assembly.GetExecutingAssembly();
Type CAType = ass.GetType(namespaceName);
var myObj = Activator.CreateInstance(CAType);
Form nextForm2 = (Form)myObj;
//second attempt
var t = Assembly
.GetExecutingAssembly()
.GetReferencedAssemblies()
.Select(x => Assembly.Load(x))
.SelectMany(x => x.GetTypes()).First(x => x.FullName == namespaceName);
var myObj2 = Activator.CreateInstance(t);
Application.Run((Form) myObj2);
}
第一次尝试返回Value cannot be null.var myObj = Activator.CreateInstance(CAType);
第二次尝试返回Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
【问题讨论】:
-
您的表单类的名称是什么?是“主要”吗?
-
是的,它是“Main”命名空间 'GlobalLib.Toolkits.XmlService{public partial class Main : Form{ ...' 请记住这是一个参考库
-
你可以试试
AppDomain.CurrentDomain.GetAssemblies()而不是Assembly.GetExecutingAssembly()。这将为您提供当前加载到 appdomain 中的所有程序集。但是您第二次尝试的例外情况为您提供了有关为什么无法实例化该类型的信息,请查看它所说的内容。 -
@Houlahan:在您的第一次尝试中,ass.GetType() 返回 null,对吧?
标签: c# winforms reflection class-library