Compact Framework - 如何动态创建没有默认构造函数的类型?
我正在使用.NET CF 3.5。我想要创建的类型没有默认构造函数,因此我想将字符串传递给重载的构造函数。我该怎么做?
代码:
Assembly a = Assembly.LoadFrom("my.dll");
Type t = a.GetType("type info here");
// All ok so far, assembly loads and I can get my type
string s = "Pass me to the constructor of Type t";
MyObj o = Activator.CreateInstance(t); // throws MissMethodException
I'm using the .NET CF 3.5. The type I want to create does not have a default constructor so I want to pass a string to an overloaded constructor. How do I do this?
Code:
Assembly a = Assembly.LoadFrom("my.dll");
Type t = a.GetType("type info here");
// All ok so far, assembly loads and I can get my type
string s = "Pass me to the constructor of Type t";
MyObj o = Activator.CreateInstance(t); // throws MissMethodException
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,这里有一个时髦的帮助器方法,它为您提供了一种灵活的方法来激活给定参数数组的类型:
您可以这样调用它:
因此,您将程序集和类型名称作为前两个参数传递,然后将所有参数传递给它。构造函数的参数按顺序排列。
Ok, here's a funky helper method to give you a flexible way to activate a type given an array of parameters:
And you call it like this:
So you pass the assembly and the name of the type as the first two parameters, and then all the constructor's parameters in order.
看看这是否适合您(未经测试):
如果该类型有多个构造函数,那么您可能需要做一些花哨的步骤来找到接受字符串参数的构造函数。
编辑:刚刚测试了代码,它可以工作。
编辑2: 克里斯的回答< /a> 显示了我所说的花式步法! ;-)
See if this works for you (untested):
If the type has more than one constructor then you may have to do some fancy footwork to find the one that accepts your string parameter.
Edit: Just tested the code, and it works.
Edit2: Chris' answer shows the fancy footwork I was talking about! ;-)