繁体   English   中英

Compact Framework - 如何在没有默认构造函数的情况下动态创建类型?

[英]Compact Framework - how do I dynamically create type with no default constructor?

我正在使用 .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
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 });

@Jonathan因为紧凑框架必须尽可能的薄。 如果还有另一种方法(例如我发布的代码),那么它们通常不会复制该功能。

Rory Blyth曾经将Compact Framework描述为“ System.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: 克里斯的回答显示了我正在谈论的花哨步法! ;-)

最短的方法:

    static object GetInstanceFromParameters(Assembly a, string typeName, params object[] pars) =>
        a.GetType(typeName).GetConstructor(pars.Select(p => p.GetType()).ToArray())?.Invoke(pars);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM