紧凑的框架如何动态创建的类型没有default constructor?
-
09-06-2019 - |
题
我使用。净CF3.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
解决方案
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 });
其他提示
@因为乔纳森的紧凑的框架,有尽可能苗条的,因为可能。如果有另一种方式做什么(如代码我贴)然后,他们一般不重复的功能。
罗里*布莱斯,曾经描述契约框架,作为"包装系统。NotImplementedExcetion".:)
好吧,这里的一个时髦的辅助方法给你一个灵活的方式来激活一类给出一系列参数:
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;
所以你通过大会和名称的类型作为第一个两个参数,然后所有的构造就是参数,以便。
看到如果这对你的作品(未经测试):
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: 克里斯的回答 表示看法,我说的!;-)
不隶属于 StackOverflow