【问题标题】:Compact Framework - how do I dynamically create type with no default constructor?Compact Framework - 如何在没有默认构造函数的情况下动态创建类型?
【发布时间】:2010-09-06 23:08:51
【问题描述】:
我正在使用 .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
【问题讨论】:
标签:
c#
reflection
compact-framework
【解决方案1】:
MyObj o = null;
Assembly a = Assembly.LoadFrom("my.dll");
Type t = a.GetType("type info here");
ConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(string) });
if(ctor != null)
o = ctor.Invoke(new object[] { s });
【解决方案2】:
好的,这是一个时髦的辅助方法,可以灵活地激活给定参数数组的类型:
static object GetInstanceFromParameters(Assembly a, string typeName, params object[] pars)
{
var t = a.GetType(typeName);
var c = t.GetConstructor(pars.Select(p => p.GetType()).ToArray());
if (c == null) return null;
return c.Invoke(pars);
}
你这样称呼它:
Foo f = GetInstanceFromParameters(a, "SmartDeviceProject1.Foo", "hello", 17) as Foo;
所以你将程序集和类型的名称作为前两个参数传递,然后依次传递所有构造函数的参数。
【解决方案3】:
看看这是否适合你(未经测试):
Type t = a.GetType("type info here");
var ctors = t.GetConstructors();
string s = "Pass me to the ctor of t";
MyObj o = ctors[0].Invoke(new[] { s }) as MyObj;
如果该类型有多个构造函数,那么您可能需要做一些花哨的工作才能找到接受您的字符串参数的那个。
编辑:刚刚测试了代码,它可以工作。
Edit2:Chris' answer 展示了我所说的花哨的步法! ;-)