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

前端 未结 3 1826
悲哀的现实
悲哀的现实 2020-12-20 21:20

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?

3条回答
  •  没有蜡笔的小新
    2020-12-20 21:37

    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.

提交回复
热议问题