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

白昼怎懂夜的黑 提交于 2019-11-28 07:47:00

问题


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

回答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:


Ok, here's a funky helper method to give you a flexible way to activate a type given an array of parameters:

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);
}

And you call it like this:

Foo f = GetInstanceFromParameters(a, "SmartDeviceProject1.Foo", "hello", 17) as Foo;

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.




回答3:


See if this works for you (untested):

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;

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! ;-)



来源:https://stackoverflow.com/questions/29436/compact-framework-how-do-i-dynamically-create-type-with-no-default-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!