Compact Framework-如何在没有默认构造函数的情况下动态创建类型?
时间:2020-03-05 18:43:38 来源:igfitidea点击:
我正在使用.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
解决方案
回答
看看这是否对我们有效(未试用):
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:克里斯的回答显示了我在说的花哨的步法! ;-)
回答
@Jonathan因为紧凑框架必须尽可能的薄。如果还有另一种方法(例如我发布的代码),那么它们通常不会复制该功能。
Rory Blyth曾经将Compact Framework描述为" System.NotImplementedExcetion的包装"。 :)
回答
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 });
回答
好的,这是一个时髦的辅助方法,可为我们提供一种灵活的方式来激活给定参数数组的类型:
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;
因此,我们将程序集和类型的名称作为前两个参数传递,然后按顺序传递所有构造函数的参数。